Add missing standard headers. Patch by Joerg Sonnenberger!
[oota-llvm.git] / lib / MC / MCParser / AsmParser.cpp
1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class implements the parser for assembly files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmParser.h"
34 #include <cctype>
35 #include <vector>
36 using namespace llvm;
37
38 namespace {
39
40 /// \brief Helper class for tracking macro definitions.
41 struct Macro {
42   StringRef Name;
43   StringRef Body;
44
45 public:
46   Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
47 };
48
49 /// \brief Helper class for storing information about an active macro
50 /// instantiation.
51 struct MacroInstantiation {
52   /// The macro being instantiated.
53   const Macro *TheMacro;
54
55   /// The macro instantiation with substitutions.
56   MemoryBuffer *Instantiation;
57
58   /// The location of the instantiation.
59   SMLoc InstantiationLoc;
60
61   /// The location where parsing should resume upon instantiation completion.
62   SMLoc ExitLoc;
63
64 public:
65   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66                      const std::vector<std::vector<AsmToken> > &A);
67 };
68
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71   friend class GenericAsmParser;
72
73   AsmParser(const AsmParser &);   // DO NOT IMPLEMENT
74   void operator=(const AsmParser &);  // DO NOT IMPLEMENT
75 private:
76   AsmLexer Lexer;
77   MCContext &Ctx;
78   MCStreamer &Out;
79   SourceMgr &SrcMgr;
80   MCAsmParserExtension *GenericParser;
81   MCAsmParserExtension *PlatformParser;
82
83   /// This is the current buffer index we're lexing from as managed by the
84   /// SourceMgr object.
85   int CurBuffer;
86
87   AsmCond TheCondState;
88   std::vector<AsmCond> TheCondStack;
89
90   /// DirectiveMap - This is a table handlers for directives.  Each handler is
91   /// invoked after the directive identifier is read and is responsible for
92   /// parsing and validating the rest of the directive.  The handler is passed
93   /// in the directive name and the location of the directive keyword.
94   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
95
96   /// MacroMap - Map of currently defined macros.
97   StringMap<Macro*> MacroMap;
98
99   /// ActiveMacros - Stack of active macro instantiations.
100   std::vector<MacroInstantiation*> ActiveMacros;
101
102   /// Boolean tracking whether macro substitution is enabled.
103   unsigned MacrosEnabled : 1;
104
105   /// Flag tracking whether any errors have been encountered.
106   unsigned HadError : 1;
107
108 public:
109   AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110             const MCAsmInfo &MAI);
111   ~AsmParser();
112
113   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
114
115   void AddDirectiveHandler(MCAsmParserExtension *Object,
116                            StringRef Directive,
117                            DirectiveHandler Handler) {
118     DirectiveMap[Directive] = std::make_pair(Object, Handler);
119   }
120
121 public:
122   /// @name MCAsmParser Interface
123   /// {
124
125   virtual SourceMgr &getSourceManager() { return SrcMgr; }
126   virtual MCAsmLexer &getLexer() { return Lexer; }
127   virtual MCContext &getContext() { return Ctx; }
128   virtual MCStreamer &getStreamer() { return Out; }
129
130   virtual void Warning(SMLoc L, const Twine &Meg);
131   virtual bool Error(SMLoc L, const Twine &Msg);
132
133   const AsmToken &Lex();
134
135   bool ParseExpression(const MCExpr *&Res);
136   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138   virtual bool ParseAbsoluteExpression(int64_t &Res);
139
140   /// }
141
142 private:
143   void CheckForValidSection();
144
145   bool ParseStatement();
146
147   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
148   void HandleMacroExit();
149
150   void PrintMacroInstantiations();
151   void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
152     SrcMgr.PrintMessage(Loc, Msg, Type);
153   }
154
155   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
156   bool EnterIncludeFile(const std::string &Filename);
157
158   /// \brief Reset the current lexer position to that given by \arg Loc. The
159   /// current token is not set; clients should ensure Lex() is called
160   /// subsequently.
161   void JumpToLoc(SMLoc Loc);
162
163   void EatToEndOfStatement();
164
165   /// \brief Parse up to the end of statement and a return the contents from the
166   /// current token until the end of the statement; the current token on exit
167   /// will be either the EndOfStatement or EOF.
168   StringRef ParseStringToEndOfStatement();
169
170   bool ParseAssignment(StringRef Name);
171
172   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
173   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
174   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
175
176   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
177   /// and set \arg Res to the identifier contents.
178   bool ParseIdentifier(StringRef &Res);
179
180   // Directive Parsing.
181
182  // ".ascii", ".asciiz", ".string"
183   bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
184   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
185   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
186   bool ParseDirectiveFill(); // ".fill"
187   bool ParseDirectiveSpace(); // ".space"
188   bool ParseDirectiveZero(); // ".zero"
189   bool ParseDirectiveSet(StringRef IDVal); // ".set" or ".equ"
190   bool ParseDirectiveOrg(); // ".org"
191   // ".align{,32}", ".p2align{,w,l}"
192   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
193
194   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
195   /// accepts a single symbol (which should be a label or an external).
196   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
197
198   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
199
200   bool ParseDirectiveAbort(); // ".abort"
201   bool ParseDirectiveInclude(); // ".include"
202
203   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
204   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
205   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
206   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
207
208   /// ParseEscapedString - Parse the current token as a string which may include
209   /// escaped characters and return the string contents.
210   bool ParseEscapedString(std::string &Data);
211
212   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
213                                     MCSymbolRefExpr::VariantKind Variant);
214 };
215
216 /// \brief Generic implementations of directive handling, etc. which is shared
217 /// (or the default, at least) for all assembler parser.
218 class GenericAsmParser : public MCAsmParserExtension {
219   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
220   void AddDirectiveHandler(StringRef Directive) {
221     getParser().AddDirectiveHandler(this, Directive,
222                                     HandleDirective<GenericAsmParser, Handler>);
223   }
224
225 public:
226   GenericAsmParser() {}
227
228   AsmParser &getParser() {
229     return (AsmParser&) this->MCAsmParserExtension::getParser();
230   }
231
232   virtual void Initialize(MCAsmParser &Parser) {
233     // Call the base implementation.
234     this->MCAsmParserExtension::Initialize(Parser);
235
236     // Debugging directives.
237     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
238     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
239     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
240     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
241
242     // CFI directives.
243     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
244                                                               ".cfi_startproc");
245     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
246                                                                 ".cfi_endproc");
247     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
248                                                          ".cfi_def_cfa_offset");
249     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
250                                                        ".cfi_def_cfa_register");
251     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
252                                                                  ".cfi_offset");
253     AddDirectiveHandler<
254      &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
255     AddDirectiveHandler<
256             &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
257
258     // Macro directives.
259     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
260       ".macros_on");
261     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
262       ".macros_off");
263     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
264     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
265     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
266
267     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
268     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
269   }
270
271   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
272   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
273   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
274   bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
275   bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
276   bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
277   bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
278   bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
279   bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
280   bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
281
282   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
283   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
284   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
285
286   bool ParseDirectiveLEB128(StringRef, SMLoc);
287 };
288
289 }
290
291 namespace llvm {
292
293 extern MCAsmParserExtension *createDarwinAsmParser();
294 extern MCAsmParserExtension *createELFAsmParser();
295 extern MCAsmParserExtension *createCOFFAsmParser();
296
297 }
298
299 enum { DEFAULT_ADDRSPACE = 0 };
300
301 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
302                      MCStreamer &_Out, const MCAsmInfo &_MAI)
303   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
304     GenericParser(new GenericAsmParser), PlatformParser(0),
305     CurBuffer(0), MacrosEnabled(true) {
306   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
307
308   // Initialize the generic parser.
309   GenericParser->Initialize(*this);
310
311   // Initialize the platform / file format parser.
312   //
313   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
314   // created.
315   if (_MAI.hasMicrosoftFastStdCallMangling()) {
316     PlatformParser = createCOFFAsmParser();
317     PlatformParser->Initialize(*this);
318   } else if (_MAI.hasSubsectionsViaSymbols()) {
319     PlatformParser = createDarwinAsmParser();
320     PlatformParser->Initialize(*this);
321   } else {
322     PlatformParser = createELFAsmParser();
323     PlatformParser->Initialize(*this);
324   }
325 }
326
327 AsmParser::~AsmParser() {
328   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
329
330   // Destroy any macros.
331   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
332          ie = MacroMap.end(); it != ie; ++it)
333     delete it->getValue();
334
335   delete PlatformParser;
336   delete GenericParser;
337 }
338
339 void AsmParser::PrintMacroInstantiations() {
340   // Print the active macro instantiation stack.
341   for (std::vector<MacroInstantiation*>::const_reverse_iterator
342          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
343     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
344                  "note");
345 }
346
347 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
348   PrintMessage(L, Msg, "warning");
349   PrintMacroInstantiations();
350 }
351
352 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
353   HadError = true;
354   PrintMessage(L, Msg, "error");
355   PrintMacroInstantiations();
356   return true;
357 }
358
359 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
360   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
361   if (NewBuf == -1)
362     return true;
363
364   CurBuffer = NewBuf;
365
366   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
367
368   return false;
369 }
370
371 void AsmParser::JumpToLoc(SMLoc Loc) {
372   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
373   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
374 }
375
376 const AsmToken &AsmParser::Lex() {
377   const AsmToken *tok = &Lexer.Lex();
378
379   if (tok->is(AsmToken::Eof)) {
380     // If this is the end of an included file, pop the parent file off the
381     // include stack.
382     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
383     if (ParentIncludeLoc != SMLoc()) {
384       JumpToLoc(ParentIncludeLoc);
385       tok = &Lexer.Lex();
386     }
387   }
388
389   if (tok->is(AsmToken::Error))
390     Error(Lexer.getErrLoc(), Lexer.getErr());
391
392   return *tok;
393 }
394
395 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
396   // Create the initial section, if requested.
397   if (!NoInitialTextSection)
398     Out.InitSections();
399
400   // Prime the lexer.
401   Lex();
402
403   HadError = false;
404   AsmCond StartingCondState = TheCondState;
405
406   // While we have input, parse each statement.
407   while (Lexer.isNot(AsmToken::Eof)) {
408     if (!ParseStatement()) continue;
409
410     // We had an error, validate that one was emitted and recover by skipping to
411     // the next line.
412     assert(HadError && "Parse statement returned an error, but none emitted!");
413     EatToEndOfStatement();
414   }
415
416   if (TheCondState.TheCond != StartingCondState.TheCond ||
417       TheCondState.Ignore != StartingCondState.Ignore)
418     return TokError("unmatched .ifs or .elses");
419
420   // Check to see there are no empty DwarfFile slots.
421   const std::vector<MCDwarfFile *> &MCDwarfFiles =
422     getContext().getMCDwarfFiles();
423   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
424     if (!MCDwarfFiles[i])
425       TokError("unassigned file number: " + Twine(i) + " for .file directives");
426   }
427
428   // Finalize the output stream if there are no errors and if the client wants
429   // us to.
430   if (!HadError && !NoFinalize)
431     Out.Finish();
432
433   return HadError;
434 }
435
436 void AsmParser::CheckForValidSection() {
437   if (!getStreamer().getCurrentSection()) {
438     TokError("expected section directive before assembly directive");
439     Out.SwitchSection(Ctx.getMachOSection(
440                         "__TEXT", "__text",
441                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
442                         0, SectionKind::getText()));
443   }
444 }
445
446 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
447 void AsmParser::EatToEndOfStatement() {
448   while (Lexer.isNot(AsmToken::EndOfStatement) &&
449          Lexer.isNot(AsmToken::Eof))
450     Lex();
451
452   // Eat EOL.
453   if (Lexer.is(AsmToken::EndOfStatement))
454     Lex();
455 }
456
457 StringRef AsmParser::ParseStringToEndOfStatement() {
458   const char *Start = getTok().getLoc().getPointer();
459
460   while (Lexer.isNot(AsmToken::EndOfStatement) &&
461          Lexer.isNot(AsmToken::Eof))
462     Lex();
463
464   const char *End = getTok().getLoc().getPointer();
465   return StringRef(Start, End - Start);
466 }
467
468 /// ParseParenExpr - Parse a paren expression and return it.
469 /// NOTE: This assumes the leading '(' has already been consumed.
470 ///
471 /// parenexpr ::= expr)
472 ///
473 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
474   if (ParseExpression(Res)) return true;
475   if (Lexer.isNot(AsmToken::RParen))
476     return TokError("expected ')' in parentheses expression");
477   EndLoc = Lexer.getLoc();
478   Lex();
479   return false;
480 }
481
482 /// ParsePrimaryExpr - Parse a primary expression and return it.
483 ///  primaryexpr ::= (parenexpr
484 ///  primaryexpr ::= symbol
485 ///  primaryexpr ::= number
486 ///  primaryexpr ::= '.'
487 ///  primaryexpr ::= ~,+,- primaryexpr
488 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
489   switch (Lexer.getKind()) {
490   default:
491     return TokError("unknown token in expression");
492   case AsmToken::Exclaim:
493     Lex(); // Eat the operator.
494     if (ParsePrimaryExpr(Res, EndLoc))
495       return true;
496     Res = MCUnaryExpr::CreateLNot(Res, getContext());
497     return false;
498   case AsmToken::Dollar:
499   case AsmToken::String:
500   case AsmToken::Identifier: {
501     EndLoc = Lexer.getLoc();
502
503     StringRef Identifier;
504     if (ParseIdentifier(Identifier))
505       return false;
506
507     // This is a symbol reference.
508     std::pair<StringRef, StringRef> Split = Identifier.split('@');
509     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
510
511     // Lookup the symbol variant if used.
512     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
513     if (Split.first.size() != Identifier.size()) {
514       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
515       if (Variant == MCSymbolRefExpr::VK_Invalid) {
516         Variant = MCSymbolRefExpr::VK_None;
517         TokError("invalid variant '" + Split.second + "'");
518       }
519     }
520
521     // If this is an absolute variable reference, substitute it now to preserve
522     // semantics in the face of reassignment.
523     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
524       if (Variant)
525         return Error(EndLoc, "unexpected modifier on variable reference");
526
527       Res = Sym->getVariableValue();
528       return false;
529     }
530
531     // Otherwise create a symbol ref.
532     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
533     return false;
534   }
535   case AsmToken::Integer: {
536     SMLoc Loc = getTok().getLoc();
537     int64_t IntVal = getTok().getIntVal();
538     Res = MCConstantExpr::Create(IntVal, getContext());
539     EndLoc = Lexer.getLoc();
540     Lex(); // Eat token.
541     // Look for 'b' or 'f' following an Integer as a directional label
542     if (Lexer.getKind() == AsmToken::Identifier) {
543       StringRef IDVal = getTok().getString();
544       if (IDVal == "f" || IDVal == "b"){
545         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
546                                                       IDVal == "f" ? 1 : 0);
547         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
548                                       getContext());
549         if(IDVal == "b" && Sym->isUndefined())
550           return Error(Loc, "invalid reference to undefined symbol");
551         EndLoc = Lexer.getLoc();
552         Lex(); // Eat identifier.
553       }
554     }
555     return false;
556   }
557   case AsmToken::Dot: {
558     // This is a '.' reference, which references the current PC.  Emit a
559     // temporary label to the streamer and refer to it.
560     MCSymbol *Sym = Ctx.CreateTempSymbol();
561     Out.EmitLabel(Sym);
562     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
563     EndLoc = Lexer.getLoc();
564     Lex(); // Eat identifier.
565     return false;
566   }
567
568   case AsmToken::LParen:
569     Lex(); // Eat the '('.
570     return ParseParenExpr(Res, EndLoc);
571   case AsmToken::Minus:
572     Lex(); // Eat the operator.
573     if (ParsePrimaryExpr(Res, EndLoc))
574       return true;
575     Res = MCUnaryExpr::CreateMinus(Res, getContext());
576     return false;
577   case AsmToken::Plus:
578     Lex(); // Eat the operator.
579     if (ParsePrimaryExpr(Res, EndLoc))
580       return true;
581     Res = MCUnaryExpr::CreatePlus(Res, getContext());
582     return false;
583   case AsmToken::Tilde:
584     Lex(); // Eat the operator.
585     if (ParsePrimaryExpr(Res, EndLoc))
586       return true;
587     Res = MCUnaryExpr::CreateNot(Res, getContext());
588     return false;
589   }
590 }
591
592 bool AsmParser::ParseExpression(const MCExpr *&Res) {
593   SMLoc EndLoc;
594   return ParseExpression(Res, EndLoc);
595 }
596
597 const MCExpr *
598 AsmParser::ApplyModifierToExpr(const MCExpr *E,
599                                MCSymbolRefExpr::VariantKind Variant) {
600   // Recurse over the given expression, rebuilding it to apply the given variant
601   // if there is exactly one symbol.
602   switch (E->getKind()) {
603   case MCExpr::Target:
604   case MCExpr::Constant:
605     return 0;
606
607   case MCExpr::SymbolRef: {
608     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
609
610     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
611       TokError("invalid variant on expression '" +
612                getTok().getIdentifier() + "' (already modified)");
613       return E;
614     }
615
616     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
617   }
618
619   case MCExpr::Unary: {
620     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
621     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
622     if (!Sub)
623       return 0;
624     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
625   }
626
627   case MCExpr::Binary: {
628     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
629     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
630     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
631
632     if (!LHS && !RHS)
633       return 0;
634
635     if (!LHS) LHS = BE->getLHS();
636     if (!RHS) RHS = BE->getRHS();
637
638     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
639   }
640   }
641
642   assert(0 && "Invalid expression kind!");
643   return 0;
644 }
645
646 /// ParseExpression - Parse an expression and return it.
647 ///
648 ///  expr ::= expr +,- expr          -> lowest.
649 ///  expr ::= expr |,^,&,! expr      -> middle.
650 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
651 ///  expr ::= primaryexpr
652 ///
653 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
654   // Parse the expression.
655   Res = 0;
656   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
657     return true;
658
659   // As a special case, we support 'a op b @ modifier' by rewriting the
660   // expression to include the modifier. This is inefficient, but in general we
661   // expect users to use 'a@modifier op b'.
662   if (Lexer.getKind() == AsmToken::At) {
663     Lex();
664
665     if (Lexer.isNot(AsmToken::Identifier))
666       return TokError("unexpected symbol modifier following '@'");
667
668     MCSymbolRefExpr::VariantKind Variant =
669       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
670     if (Variant == MCSymbolRefExpr::VK_Invalid)
671       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
672
673     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
674     if (!ModifiedRes) {
675       return TokError("invalid modifier '" + getTok().getIdentifier() +
676                       "' (no symbols present)");
677       return true;
678     }
679
680     Res = ModifiedRes;
681     Lex();
682   }
683
684   // Try to constant fold it up front, if possible.
685   int64_t Value;
686   if (Res->EvaluateAsAbsolute(Value))
687     Res = MCConstantExpr::Create(Value, getContext());
688
689   return false;
690 }
691
692 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
693   Res = 0;
694   return ParseParenExpr(Res, EndLoc) ||
695          ParseBinOpRHS(1, Res, EndLoc);
696 }
697
698 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
699   const MCExpr *Expr;
700
701   SMLoc StartLoc = Lexer.getLoc();
702   if (ParseExpression(Expr))
703     return true;
704
705   if (!Expr->EvaluateAsAbsolute(Res))
706     return Error(StartLoc, "expected absolute expression");
707
708   return false;
709 }
710
711 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
712                                    MCBinaryExpr::Opcode &Kind) {
713   switch (K) {
714   default:
715     return 0;    // not a binop.
716
717     // Lowest Precedence: &&, ||, @
718   case AsmToken::AmpAmp:
719     Kind = MCBinaryExpr::LAnd;
720     return 1;
721   case AsmToken::PipePipe:
722     Kind = MCBinaryExpr::LOr;
723     return 1;
724
725
726     // Low Precedence: |, &, ^
727     //
728     // FIXME: gas seems to support '!' as an infix operator?
729   case AsmToken::Pipe:
730     Kind = MCBinaryExpr::Or;
731     return 2;
732   case AsmToken::Caret:
733     Kind = MCBinaryExpr::Xor;
734     return 2;
735   case AsmToken::Amp:
736     Kind = MCBinaryExpr::And;
737     return 2;
738
739     // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
740   case AsmToken::EqualEqual:
741     Kind = MCBinaryExpr::EQ;
742     return 3;
743   case AsmToken::ExclaimEqual:
744   case AsmToken::LessGreater:
745     Kind = MCBinaryExpr::NE;
746     return 3;
747   case AsmToken::Less:
748     Kind = MCBinaryExpr::LT;
749     return 3;
750   case AsmToken::LessEqual:
751     Kind = MCBinaryExpr::LTE;
752     return 3;
753   case AsmToken::Greater:
754     Kind = MCBinaryExpr::GT;
755     return 3;
756   case AsmToken::GreaterEqual:
757     Kind = MCBinaryExpr::GTE;
758     return 3;
759
760     // High Intermediate Precedence: +, -
761   case AsmToken::Plus:
762     Kind = MCBinaryExpr::Add;
763     return 4;
764   case AsmToken::Minus:
765     Kind = MCBinaryExpr::Sub;
766     return 4;
767
768     // Highest Precedence: *, /, %, <<, >>
769   case AsmToken::Star:
770     Kind = MCBinaryExpr::Mul;
771     return 5;
772   case AsmToken::Slash:
773     Kind = MCBinaryExpr::Div;
774     return 5;
775   case AsmToken::Percent:
776     Kind = MCBinaryExpr::Mod;
777     return 5;
778   case AsmToken::LessLess:
779     Kind = MCBinaryExpr::Shl;
780     return 5;
781   case AsmToken::GreaterGreater:
782     Kind = MCBinaryExpr::Shr;
783     return 5;
784   }
785 }
786
787
788 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
789 /// Res contains the LHS of the expression on input.
790 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
791                               SMLoc &EndLoc) {
792   while (1) {
793     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
794     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
795
796     // If the next token is lower precedence than we are allowed to eat, return
797     // successfully with what we ate already.
798     if (TokPrec < Precedence)
799       return false;
800
801     Lex();
802
803     // Eat the next primary expression.
804     const MCExpr *RHS;
805     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
806
807     // If BinOp binds less tightly with RHS than the operator after RHS, let
808     // the pending operator take RHS as its LHS.
809     MCBinaryExpr::Opcode Dummy;
810     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
811     if (TokPrec < NextTokPrec) {
812       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
813     }
814
815     // Merge LHS and RHS according to operator.
816     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
817   }
818 }
819
820
821
822
823 /// ParseStatement:
824 ///   ::= EndOfStatement
825 ///   ::= Label* Directive ...Operands... EndOfStatement
826 ///   ::= Label* Identifier OperandList* EndOfStatement
827 bool AsmParser::ParseStatement() {
828   if (Lexer.is(AsmToken::EndOfStatement)) {
829     Out.AddBlankLine();
830     Lex();
831     return false;
832   }
833
834   // Statements always start with an identifier.
835   AsmToken ID = getTok();
836   SMLoc IDLoc = ID.getLoc();
837   StringRef IDVal;
838   int64_t LocalLabelVal = -1;
839   // GUESS allow an integer followed by a ':' as a directional local label
840   if (Lexer.is(AsmToken::Integer)) {
841     LocalLabelVal = getTok().getIntVal();
842     if (LocalLabelVal < 0) {
843       if (!TheCondState.Ignore)
844         return TokError("unexpected token at start of statement");
845       IDVal = "";
846     }
847     else {
848       IDVal = getTok().getString();
849       Lex(); // Consume the integer token to be used as an identifier token.
850       if (Lexer.getKind() != AsmToken::Colon) {
851         if (!TheCondState.Ignore)
852           return TokError("unexpected token at start of statement");
853       }
854     }
855   }
856   else if (ParseIdentifier(IDVal)) {
857     if (!TheCondState.Ignore)
858       return TokError("unexpected token at start of statement");
859     IDVal = "";
860   }
861
862   // Handle conditional assembly here before checking for skipping.  We
863   // have to do this so that .endif isn't skipped in a ".if 0" block for
864   // example.
865   if (IDVal == ".if")
866     return ParseDirectiveIf(IDLoc);
867   if (IDVal == ".elseif")
868     return ParseDirectiveElseIf(IDLoc);
869   if (IDVal == ".else")
870     return ParseDirectiveElse(IDLoc);
871   if (IDVal == ".endif")
872     return ParseDirectiveEndIf(IDLoc);
873
874   // If we are in a ".if 0" block, ignore this statement.
875   if (TheCondState.Ignore) {
876     EatToEndOfStatement();
877     return false;
878   }
879
880   // FIXME: Recurse on local labels?
881
882   // See what kind of statement we have.
883   switch (Lexer.getKind()) {
884   case AsmToken::Colon: {
885     CheckForValidSection();
886
887     // identifier ':'   -> Label.
888     Lex();
889
890     // Diagnose attempt to use a variable as a label.
891     //
892     // FIXME: Diagnostics. Note the location of the definition as a label.
893     // FIXME: This doesn't diagnose assignment to a symbol which has been
894     // implicitly marked as external.
895     MCSymbol *Sym;
896     if (LocalLabelVal == -1)
897       Sym = getContext().GetOrCreateSymbol(IDVal);
898     else
899       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
900     if (!Sym->isUndefined() || Sym->isVariable())
901       return Error(IDLoc, "invalid symbol redefinition");
902
903     // Emit the label.
904     Out.EmitLabel(Sym);
905
906     // Consume any end of statement token, if present, to avoid spurious
907     // AddBlankLine calls().
908     if (Lexer.is(AsmToken::EndOfStatement)) {
909       Lex();
910       if (Lexer.is(AsmToken::Eof))
911         return false;
912     }
913
914     return ParseStatement();
915   }
916
917   case AsmToken::Equal:
918     // identifier '=' ... -> assignment statement
919     Lex();
920
921     return ParseAssignment(IDVal);
922
923   default: // Normal instruction or directive.
924     break;
925   }
926
927   // If macros are enabled, check to see if this is a macro instantiation.
928   if (MacrosEnabled)
929     if (const Macro *M = MacroMap.lookup(IDVal))
930       return HandleMacroEntry(IDVal, IDLoc, M);
931
932   // Otherwise, we have a normal instruction or directive.
933   if (IDVal[0] == '.') {
934     // Assembler features
935     if (IDVal == ".set" || IDVal == ".equ")
936       return ParseDirectiveSet(IDVal);
937
938     // Data directives
939
940     if (IDVal == ".ascii")
941       return ParseDirectiveAscii(IDVal, false);
942     if (IDVal == ".asciz" || IDVal == ".string")
943       return ParseDirectiveAscii(IDVal, true);
944
945     if (IDVal == ".byte")
946       return ParseDirectiveValue(1);
947     if (IDVal == ".short")
948       return ParseDirectiveValue(2);
949     if (IDVal == ".value")
950       return ParseDirectiveValue(2);
951     if (IDVal == ".2byte")
952       return ParseDirectiveValue(2);
953     if (IDVal == ".long")
954       return ParseDirectiveValue(4);
955     if (IDVal == ".int")
956       return ParseDirectiveValue(4);
957     if (IDVal == ".4byte")
958       return ParseDirectiveValue(4);
959     if (IDVal == ".quad")
960       return ParseDirectiveValue(8);
961     if (IDVal == ".8byte")
962       return ParseDirectiveValue(8);
963     if (IDVal == ".single")
964       return ParseDirectiveRealValue(APFloat::IEEEsingle);
965     if (IDVal == ".double")
966       return ParseDirectiveRealValue(APFloat::IEEEdouble);
967
968     if (IDVal == ".align") {
969       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
970       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
971     }
972     if (IDVal == ".align32") {
973       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
974       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
975     }
976     if (IDVal == ".balign")
977       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
978     if (IDVal == ".balignw")
979       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
980     if (IDVal == ".balignl")
981       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
982     if (IDVal == ".p2align")
983       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
984     if (IDVal == ".p2alignw")
985       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
986     if (IDVal == ".p2alignl")
987       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
988
989     if (IDVal == ".org")
990       return ParseDirectiveOrg();
991
992     if (IDVal == ".fill")
993       return ParseDirectiveFill();
994     if (IDVal == ".space")
995       return ParseDirectiveSpace();
996     if (IDVal == ".zero")
997       return ParseDirectiveZero();
998
999     // Symbol attribute directives
1000
1001     if (IDVal == ".globl" || IDVal == ".global")
1002       return ParseDirectiveSymbolAttribute(MCSA_Global);
1003     // ELF only? Should it be here?
1004     if (IDVal == ".local")
1005       return ParseDirectiveSymbolAttribute(MCSA_Local);
1006     if (IDVal == ".hidden")
1007       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1008     if (IDVal == ".indirect_symbol")
1009       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1010     if (IDVal == ".internal")
1011       return ParseDirectiveSymbolAttribute(MCSA_Internal);
1012     if (IDVal == ".lazy_reference")
1013       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1014     if (IDVal == ".no_dead_strip")
1015       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1016     if (IDVal == ".symbol_resolver")
1017       return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1018     if (IDVal == ".private_extern")
1019       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1020     if (IDVal == ".protected")
1021       return ParseDirectiveSymbolAttribute(MCSA_Protected);
1022     if (IDVal == ".reference")
1023       return ParseDirectiveSymbolAttribute(MCSA_Reference);
1024     if (IDVal == ".weak")
1025       return ParseDirectiveSymbolAttribute(MCSA_Weak);
1026     if (IDVal == ".weak_definition")
1027       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1028     if (IDVal == ".weak_reference")
1029       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1030     if (IDVal == ".weak_def_can_be_hidden")
1031       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1032
1033     if (IDVal == ".comm")
1034       return ParseDirectiveComm(/*IsLocal=*/false);
1035     if (IDVal == ".lcomm")
1036       return ParseDirectiveComm(/*IsLocal=*/true);
1037
1038     if (IDVal == ".abort")
1039       return ParseDirectiveAbort();
1040     if (IDVal == ".include")
1041       return ParseDirectiveInclude();
1042
1043     // Look up the handler in the handler table.
1044     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1045       DirectiveMap.lookup(IDVal);
1046     if (Handler.first)
1047       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1048
1049     // Target hook for parsing target specific directives.
1050     if (!getTargetParser().ParseDirective(ID))
1051       return false;
1052
1053     Warning(IDLoc, "ignoring directive for now");
1054     EatToEndOfStatement();
1055     return false;
1056   }
1057
1058   CheckForValidSection();
1059
1060   // Canonicalize the opcode to lower case.
1061   SmallString<128> Opcode;
1062   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1063     Opcode.push_back(tolower(IDVal[i]));
1064
1065   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1066   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1067                                                      ParsedOperands);
1068
1069   // Dump the parsed representation, if requested.
1070   if (getShowParsedOperands()) {
1071     SmallString<256> Str;
1072     raw_svector_ostream OS(Str);
1073     OS << "parsed instruction: [";
1074     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1075       if (i != 0)
1076         OS << ", ";
1077       ParsedOperands[i]->dump(OS);
1078     }
1079     OS << "]";
1080
1081     PrintMessage(IDLoc, OS.str(), "note");
1082   }
1083
1084   // If parsing succeeded, match the instruction.
1085   if (!HadError)
1086     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1087                                                          Out);
1088
1089   // Free any parsed operands.
1090   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1091     delete ParsedOperands[i];
1092
1093   // Don't skip the rest of the line, the instruction parser is responsible for
1094   // that.
1095   return false;
1096 }
1097
1098 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1099                                    const std::vector<std::vector<AsmToken> > &A)
1100   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1101 {
1102   // Macro instantiation is lexical, unfortunately. We construct a new buffer
1103   // to hold the macro body with substitutions.
1104   SmallString<256> Buf;
1105   raw_svector_ostream OS(Buf);
1106
1107   StringRef Body = M->Body;
1108   while (!Body.empty()) {
1109     // Scan for the next substitution.
1110     std::size_t End = Body.size(), Pos = 0;
1111     for (; Pos != End; ++Pos) {
1112       // Check for a substitution or escape.
1113       if (Body[Pos] != '$' || Pos + 1 == End)
1114         continue;
1115
1116       char Next = Body[Pos + 1];
1117       if (Next == '$' || Next == 'n' || isdigit(Next))
1118         break;
1119     }
1120
1121     // Add the prefix.
1122     OS << Body.slice(0, Pos);
1123
1124     // Check if we reached the end.
1125     if (Pos == End)
1126       break;
1127
1128     switch (Body[Pos+1]) {
1129        // $$ => $
1130     case '$':
1131       OS << '$';
1132       break;
1133
1134       // $n => number of arguments
1135     case 'n':
1136       OS << A.size();
1137       break;
1138
1139        // $[0-9] => argument
1140     default: {
1141       // Missing arguments are ignored.
1142       unsigned Index = Body[Pos+1] - '0';
1143       if (Index >= A.size())
1144         break;
1145
1146       // Otherwise substitute with the token values, with spaces eliminated.
1147       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1148              ie = A[Index].end(); it != ie; ++it)
1149         OS << it->getString();
1150       break;
1151     }
1152     }
1153
1154     // Update the scan point.
1155     Body = Body.substr(Pos + 2);
1156   }
1157
1158   // We include the .endmacro in the buffer as our queue to exit the macro
1159   // instantiation.
1160   OS << ".endmacro\n";
1161
1162   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1163 }
1164
1165 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1166                                  const Macro *M) {
1167   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1168   // this, although we should protect against infinite loops.
1169   if (ActiveMacros.size() == 20)
1170     return TokError("macros cannot be nested more than 20 levels deep");
1171
1172   // Parse the macro instantiation arguments.
1173   std::vector<std::vector<AsmToken> > MacroArguments;
1174   MacroArguments.push_back(std::vector<AsmToken>());
1175   unsigned ParenLevel = 0;
1176   for (;;) {
1177     if (Lexer.is(AsmToken::Eof))
1178       return TokError("unexpected token in macro instantiation");
1179     if (Lexer.is(AsmToken::EndOfStatement))
1180       break;
1181
1182     // If we aren't inside parentheses and this is a comma, start a new token
1183     // list.
1184     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1185       MacroArguments.push_back(std::vector<AsmToken>());
1186     } else {
1187       // Adjust the current parentheses level.
1188       if (Lexer.is(AsmToken::LParen))
1189         ++ParenLevel;
1190       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1191         --ParenLevel;
1192
1193       // Append the token to the current argument list.
1194       MacroArguments.back().push_back(getTok());
1195     }
1196     Lex();
1197   }
1198
1199   // Create the macro instantiation object and add to the current macro
1200   // instantiation stack.
1201   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1202                                                   getTok().getLoc(),
1203                                                   MacroArguments);
1204   ActiveMacros.push_back(MI);
1205
1206   // Jump to the macro instantiation and prime the lexer.
1207   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1208   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1209   Lex();
1210
1211   return false;
1212 }
1213
1214 void AsmParser::HandleMacroExit() {
1215   // Jump to the EndOfStatement we should return to, and consume it.
1216   JumpToLoc(ActiveMacros.back()->ExitLoc);
1217   Lex();
1218
1219   // Pop the instantiation entry.
1220   delete ActiveMacros.back();
1221   ActiveMacros.pop_back();
1222 }
1223
1224 static void MarkUsed(const MCExpr *Value) {
1225   switch (Value->getKind()) {
1226   case MCExpr::Binary:
1227     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1228     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1229     break;
1230   case MCExpr::Target:
1231   case MCExpr::Constant:
1232     break;
1233   case MCExpr::SymbolRef: {
1234     static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1235     break;
1236   }
1237   case MCExpr::Unary:
1238     MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1239     break;
1240   }
1241 }
1242
1243 bool AsmParser::ParseAssignment(StringRef Name) {
1244   // FIXME: Use better location, we should use proper tokens.
1245   SMLoc EqualLoc = Lexer.getLoc();
1246
1247   const MCExpr *Value;
1248   if (ParseExpression(Value))
1249     return true;
1250
1251   MarkUsed(Value);
1252
1253   if (Lexer.isNot(AsmToken::EndOfStatement))
1254     return TokError("unexpected token in assignment");
1255
1256   // Eat the end of statement marker.
1257   Lex();
1258
1259   // Validate that the LHS is allowed to be a variable (either it has not been
1260   // used as a symbol, or it is an absolute symbol).
1261   MCSymbol *Sym = getContext().LookupSymbol(Name);
1262   if (Sym) {
1263     // Diagnose assignment to a label.
1264     //
1265     // FIXME: Diagnostics. Note the location of the definition as a label.
1266     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1267     if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1268       ; // Allow redefinitions of undefined symbols only used in directives.
1269     else if (!Sym->isUndefined() && !Sym->isAbsolute())
1270       return Error(EqualLoc, "redefinition of '" + Name + "'");
1271     else if (!Sym->isVariable())
1272       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1273     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1274       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1275                    Name + "'");
1276
1277     // Don't count these checks as uses.
1278     Sym->setUsed(false);
1279   } else
1280     Sym = getContext().GetOrCreateSymbol(Name);
1281
1282   // FIXME: Handle '.'.
1283
1284   // Do the assignment.
1285   Out.EmitAssignment(Sym, Value);
1286
1287   return false;
1288 }
1289
1290 /// ParseIdentifier:
1291 ///   ::= identifier
1292 ///   ::= string
1293 bool AsmParser::ParseIdentifier(StringRef &Res) {
1294   // The assembler has relaxed rules for accepting identifiers, in particular we
1295   // allow things like '.globl $foo', which would normally be separate
1296   // tokens. At this level, we have already lexed so we cannot (currently)
1297   // handle this as a context dependent token, instead we detect adjacent tokens
1298   // and return the combined identifier.
1299   if (Lexer.is(AsmToken::Dollar)) {
1300     SMLoc DollarLoc = getLexer().getLoc();
1301
1302     // Consume the dollar sign, and check for a following identifier.
1303     Lex();
1304     if (Lexer.isNot(AsmToken::Identifier))
1305       return true;
1306
1307     // We have a '$' followed by an identifier, make sure they are adjacent.
1308     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1309       return true;
1310
1311     // Construct the joined identifier and consume the token.
1312     Res = StringRef(DollarLoc.getPointer(),
1313                     getTok().getIdentifier().size() + 1);
1314     Lex();
1315     return false;
1316   }
1317
1318   if (Lexer.isNot(AsmToken::Identifier) &&
1319       Lexer.isNot(AsmToken::String))
1320     return true;
1321
1322   Res = getTok().getIdentifier();
1323
1324   Lex(); // Consume the identifier token.
1325
1326   return false;
1327 }
1328
1329 /// ParseDirectiveSet:
1330 ///   ::= .set identifier ',' expression
1331 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1332   StringRef Name;
1333
1334   if (ParseIdentifier(Name))
1335     return TokError("expected identifier after '" + Twine(IDVal) + "'");
1336
1337   if (getLexer().isNot(AsmToken::Comma))
1338     return TokError("unexpected token in '" + Twine(IDVal) + "'");
1339   Lex();
1340
1341   return ParseAssignment(Name);
1342 }
1343
1344 bool AsmParser::ParseEscapedString(std::string &Data) {
1345   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1346
1347   Data = "";
1348   StringRef Str = getTok().getStringContents();
1349   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1350     if (Str[i] != '\\') {
1351       Data += Str[i];
1352       continue;
1353     }
1354
1355     // Recognize escaped characters. Note that this escape semantics currently
1356     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1357     ++i;
1358     if (i == e)
1359       return TokError("unexpected backslash at end of string");
1360
1361     // Recognize octal sequences.
1362     if ((unsigned) (Str[i] - '0') <= 7) {
1363       // Consume up to three octal characters.
1364       unsigned Value = Str[i] - '0';
1365
1366       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1367         ++i;
1368         Value = Value * 8 + (Str[i] - '0');
1369
1370         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1371           ++i;
1372           Value = Value * 8 + (Str[i] - '0');
1373         }
1374       }
1375
1376       if (Value > 255)
1377         return TokError("invalid octal escape sequence (out of range)");
1378
1379       Data += (unsigned char) Value;
1380       continue;
1381     }
1382
1383     // Otherwise recognize individual escapes.
1384     switch (Str[i]) {
1385     default:
1386       // Just reject invalid escape sequences for now.
1387       return TokError("invalid escape sequence (unrecognized character)");
1388
1389     case 'b': Data += '\b'; break;
1390     case 'f': Data += '\f'; break;
1391     case 'n': Data += '\n'; break;
1392     case 'r': Data += '\r'; break;
1393     case 't': Data += '\t'; break;
1394     case '"': Data += '"'; break;
1395     case '\\': Data += '\\'; break;
1396     }
1397   }
1398
1399   return false;
1400 }
1401
1402 /// ParseDirectiveAscii:
1403 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1404 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1405   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1406     CheckForValidSection();
1407
1408     for (;;) {
1409       if (getLexer().isNot(AsmToken::String))
1410         return TokError("expected string in '" + Twine(IDVal) + "' directive");
1411
1412       std::string Data;
1413       if (ParseEscapedString(Data))
1414         return true;
1415
1416       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1417       if (ZeroTerminated)
1418         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1419
1420       Lex();
1421
1422       if (getLexer().is(AsmToken::EndOfStatement))
1423         break;
1424
1425       if (getLexer().isNot(AsmToken::Comma))
1426         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1427       Lex();
1428     }
1429   }
1430
1431   Lex();
1432   return false;
1433 }
1434
1435 /// ParseDirectiveValue
1436 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1437 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1438   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1439     CheckForValidSection();
1440
1441     for (;;) {
1442       const MCExpr *Value;
1443       if (ParseExpression(Value))
1444         return true;
1445
1446       // Special case constant expressions to match code generator.
1447       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1448         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1449       else
1450         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1451
1452       if (getLexer().is(AsmToken::EndOfStatement))
1453         break;
1454
1455       // FIXME: Improve diagnostic.
1456       if (getLexer().isNot(AsmToken::Comma))
1457         return TokError("unexpected token in directive");
1458       Lex();
1459     }
1460   }
1461
1462   Lex();
1463   return false;
1464 }
1465
1466 /// ParseDirectiveRealValue
1467 ///  ::= (.single | .double) [ expression (, expression)* ]
1468 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1469   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1470     CheckForValidSection();
1471
1472     for (;;) {
1473       // We don't truly support arithmetic on floating point expressions, so we
1474       // have to manually parse unary prefixes.
1475       bool IsNeg = false;
1476       if (getLexer().is(AsmToken::Minus)) {
1477         Lex();
1478         IsNeg = true;
1479       } else if (getLexer().is(AsmToken::Plus))
1480         Lex();
1481
1482       if (getLexer().isNot(AsmToken::Integer) &&
1483           getLexer().isNot(AsmToken::Real))
1484         return TokError("unexpected token in directive");
1485
1486       // Convert to an APFloat.
1487       APFloat Value(Semantics);
1488       if (Value.convertFromString(getTok().getString(),
1489                                   APFloat::rmNearestTiesToEven) ==
1490           APFloat::opInvalidOp)
1491         return TokError("invalid floating point literal");
1492       if (IsNeg)
1493         Value.changeSign();
1494
1495       // Consume the numeric token.
1496       Lex();
1497
1498       // Emit the value as an integer.
1499       APInt AsInt = Value.bitcastToAPInt();
1500       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1501                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1502
1503       if (getLexer().is(AsmToken::EndOfStatement))
1504         break;
1505
1506       if (getLexer().isNot(AsmToken::Comma))
1507         return TokError("unexpected token in directive");
1508       Lex();
1509     }
1510   }
1511
1512   Lex();
1513   return false;
1514 }
1515
1516 /// ParseDirectiveSpace
1517 ///  ::= .space expression [ , expression ]
1518 bool AsmParser::ParseDirectiveSpace() {
1519   CheckForValidSection();
1520
1521   int64_t NumBytes;
1522   if (ParseAbsoluteExpression(NumBytes))
1523     return true;
1524
1525   int64_t FillExpr = 0;
1526   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1527     if (getLexer().isNot(AsmToken::Comma))
1528       return TokError("unexpected token in '.space' directive");
1529     Lex();
1530
1531     if (ParseAbsoluteExpression(FillExpr))
1532       return true;
1533
1534     if (getLexer().isNot(AsmToken::EndOfStatement))
1535       return TokError("unexpected token in '.space' directive");
1536   }
1537
1538   Lex();
1539
1540   if (NumBytes <= 0)
1541     return TokError("invalid number of bytes in '.space' directive");
1542
1543   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1544   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1545
1546   return false;
1547 }
1548
1549 /// ParseDirectiveZero
1550 ///  ::= .zero expression
1551 bool AsmParser::ParseDirectiveZero() {
1552   CheckForValidSection();
1553
1554   int64_t NumBytes;
1555   if (ParseAbsoluteExpression(NumBytes))
1556     return true;
1557
1558   int64_t Val = 0;
1559   if (getLexer().is(AsmToken::Comma)) {
1560     Lex();
1561     if (ParseAbsoluteExpression(Val))
1562       return true;
1563   }
1564
1565   if (getLexer().isNot(AsmToken::EndOfStatement))
1566     return TokError("unexpected token in '.zero' directive");
1567
1568   Lex();
1569
1570   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1571
1572   return false;
1573 }
1574
1575 /// ParseDirectiveFill
1576 ///  ::= .fill expression , expression , expression
1577 bool AsmParser::ParseDirectiveFill() {
1578   CheckForValidSection();
1579
1580   int64_t NumValues;
1581   if (ParseAbsoluteExpression(NumValues))
1582     return true;
1583
1584   if (getLexer().isNot(AsmToken::Comma))
1585     return TokError("unexpected token in '.fill' directive");
1586   Lex();
1587
1588   int64_t FillSize;
1589   if (ParseAbsoluteExpression(FillSize))
1590     return true;
1591
1592   if (getLexer().isNot(AsmToken::Comma))
1593     return TokError("unexpected token in '.fill' directive");
1594   Lex();
1595
1596   int64_t FillExpr;
1597   if (ParseAbsoluteExpression(FillExpr))
1598     return true;
1599
1600   if (getLexer().isNot(AsmToken::EndOfStatement))
1601     return TokError("unexpected token in '.fill' directive");
1602
1603   Lex();
1604
1605   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1606     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1607
1608   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1609     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1610
1611   return false;
1612 }
1613
1614 /// ParseDirectiveOrg
1615 ///  ::= .org expression [ , expression ]
1616 bool AsmParser::ParseDirectiveOrg() {
1617   CheckForValidSection();
1618
1619   const MCExpr *Offset;
1620   if (ParseExpression(Offset))
1621     return true;
1622
1623   // Parse optional fill expression.
1624   int64_t FillExpr = 0;
1625   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1626     if (getLexer().isNot(AsmToken::Comma))
1627       return TokError("unexpected token in '.org' directive");
1628     Lex();
1629
1630     if (ParseAbsoluteExpression(FillExpr))
1631       return true;
1632
1633     if (getLexer().isNot(AsmToken::EndOfStatement))
1634       return TokError("unexpected token in '.org' directive");
1635   }
1636
1637   Lex();
1638
1639   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1640   // has to be relative to the current section.
1641   getStreamer().EmitValueToOffset(Offset, FillExpr);
1642
1643   return false;
1644 }
1645
1646 /// ParseDirectiveAlign
1647 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1648 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1649   CheckForValidSection();
1650
1651   SMLoc AlignmentLoc = getLexer().getLoc();
1652   int64_t Alignment;
1653   if (ParseAbsoluteExpression(Alignment))
1654     return true;
1655
1656   SMLoc MaxBytesLoc;
1657   bool HasFillExpr = false;
1658   int64_t FillExpr = 0;
1659   int64_t MaxBytesToFill = 0;
1660   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1661     if (getLexer().isNot(AsmToken::Comma))
1662       return TokError("unexpected token in directive");
1663     Lex();
1664
1665     // The fill expression can be omitted while specifying a maximum number of
1666     // alignment bytes, e.g:
1667     //  .align 3,,4
1668     if (getLexer().isNot(AsmToken::Comma)) {
1669       HasFillExpr = true;
1670       if (ParseAbsoluteExpression(FillExpr))
1671         return true;
1672     }
1673
1674     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1675       if (getLexer().isNot(AsmToken::Comma))
1676         return TokError("unexpected token in directive");
1677       Lex();
1678
1679       MaxBytesLoc = getLexer().getLoc();
1680       if (ParseAbsoluteExpression(MaxBytesToFill))
1681         return true;
1682
1683       if (getLexer().isNot(AsmToken::EndOfStatement))
1684         return TokError("unexpected token in directive");
1685     }
1686   }
1687
1688   Lex();
1689
1690   if (!HasFillExpr)
1691     FillExpr = 0;
1692
1693   // Compute alignment in bytes.
1694   if (IsPow2) {
1695     // FIXME: Diagnose overflow.
1696     if (Alignment >= 32) {
1697       Error(AlignmentLoc, "invalid alignment value");
1698       Alignment = 31;
1699     }
1700
1701     Alignment = 1ULL << Alignment;
1702   }
1703
1704   // Diagnose non-sensical max bytes to align.
1705   if (MaxBytesLoc.isValid()) {
1706     if (MaxBytesToFill < 1) {
1707       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1708             "many bytes, ignoring maximum bytes expression");
1709       MaxBytesToFill = 0;
1710     }
1711
1712     if (MaxBytesToFill >= Alignment) {
1713       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1714               "has no effect");
1715       MaxBytesToFill = 0;
1716     }
1717   }
1718
1719   // Check whether we should use optimal code alignment for this .align
1720   // directive.
1721   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1722   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1723       ValueSize == 1 && UseCodeAlign) {
1724     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1725   } else {
1726     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1727     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1728                                        MaxBytesToFill);
1729   }
1730
1731   return false;
1732 }
1733
1734 /// ParseDirectiveSymbolAttribute
1735 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1736 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1737   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1738     for (;;) {
1739       StringRef Name;
1740
1741       if (ParseIdentifier(Name))
1742         return TokError("expected identifier in directive");
1743
1744       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1745
1746       getStreamer().EmitSymbolAttribute(Sym, Attr);
1747
1748       if (getLexer().is(AsmToken::EndOfStatement))
1749         break;
1750
1751       if (getLexer().isNot(AsmToken::Comma))
1752         return TokError("unexpected token in directive");
1753       Lex();
1754     }
1755   }
1756
1757   Lex();
1758   return false;
1759 }
1760
1761 /// ParseDirectiveComm
1762 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1763 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1764   CheckForValidSection();
1765
1766   SMLoc IDLoc = getLexer().getLoc();
1767   StringRef Name;
1768   if (ParseIdentifier(Name))
1769     return TokError("expected identifier in directive");
1770
1771   // Handle the identifier as the key symbol.
1772   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1773
1774   if (getLexer().isNot(AsmToken::Comma))
1775     return TokError("unexpected token in directive");
1776   Lex();
1777
1778   int64_t Size;
1779   SMLoc SizeLoc = getLexer().getLoc();
1780   if (ParseAbsoluteExpression(Size))
1781     return true;
1782
1783   int64_t Pow2Alignment = 0;
1784   SMLoc Pow2AlignmentLoc;
1785   if (getLexer().is(AsmToken::Comma)) {
1786     Lex();
1787     Pow2AlignmentLoc = getLexer().getLoc();
1788     if (ParseAbsoluteExpression(Pow2Alignment))
1789       return true;
1790
1791     // If this target takes alignments in bytes (not log) validate and convert.
1792     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1793       if (!isPowerOf2_64(Pow2Alignment))
1794         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1795       Pow2Alignment = Log2_64(Pow2Alignment);
1796     }
1797   }
1798
1799   if (getLexer().isNot(AsmToken::EndOfStatement))
1800     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1801
1802   Lex();
1803
1804   // NOTE: a size of zero for a .comm should create a undefined symbol
1805   // but a size of .lcomm creates a bss symbol of size zero.
1806   if (Size < 0)
1807     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1808                  "be less than zero");
1809
1810   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1811   // may internally end up wanting an alignment in bytes.
1812   // FIXME: Diagnose overflow.
1813   if (Pow2Alignment < 0)
1814     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1815                  "alignment, can't be less than zero");
1816
1817   if (!Sym->isUndefined())
1818     return Error(IDLoc, "invalid symbol redefinition");
1819
1820   // '.lcomm' is equivalent to '.zerofill'.
1821   // Create the Symbol as a common or local common with Size and Pow2Alignment
1822   if (IsLocal) {
1823     getStreamer().EmitZerofill(Ctx.getMachOSection(
1824                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1825                                  0, SectionKind::getBSS()),
1826                                Sym, Size, 1 << Pow2Alignment);
1827     return false;
1828   }
1829
1830   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1831   return false;
1832 }
1833
1834 /// ParseDirectiveAbort
1835 ///  ::= .abort [... message ...]
1836 bool AsmParser::ParseDirectiveAbort() {
1837   // FIXME: Use loc from directive.
1838   SMLoc Loc = getLexer().getLoc();
1839
1840   StringRef Str = ParseStringToEndOfStatement();
1841   if (getLexer().isNot(AsmToken::EndOfStatement))
1842     return TokError("unexpected token in '.abort' directive");
1843
1844   Lex();
1845
1846   if (Str.empty())
1847     Error(Loc, ".abort detected. Assembly stopping.");
1848   else
1849     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1850   // FIXME: Actually abort assembly here.
1851
1852   return false;
1853 }
1854
1855 /// ParseDirectiveInclude
1856 ///  ::= .include "filename"
1857 bool AsmParser::ParseDirectiveInclude() {
1858   if (getLexer().isNot(AsmToken::String))
1859     return TokError("expected string in '.include' directive");
1860
1861   std::string Filename = getTok().getString();
1862   SMLoc IncludeLoc = getLexer().getLoc();
1863   Lex();
1864
1865   if (getLexer().isNot(AsmToken::EndOfStatement))
1866     return TokError("unexpected token in '.include' directive");
1867
1868   // Strip the quotes.
1869   Filename = Filename.substr(1, Filename.size()-2);
1870
1871   // Attempt to switch the lexer to the included file before consuming the end
1872   // of statement to avoid losing it when we switch.
1873   if (EnterIncludeFile(Filename)) {
1874     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1875     return true;
1876   }
1877
1878   return false;
1879 }
1880
1881 /// ParseDirectiveIf
1882 /// ::= .if expression
1883 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1884   TheCondStack.push_back(TheCondState);
1885   TheCondState.TheCond = AsmCond::IfCond;
1886   if(TheCondState.Ignore) {
1887     EatToEndOfStatement();
1888   }
1889   else {
1890     int64_t ExprValue;
1891     if (ParseAbsoluteExpression(ExprValue))
1892       return true;
1893
1894     if (getLexer().isNot(AsmToken::EndOfStatement))
1895       return TokError("unexpected token in '.if' directive");
1896
1897     Lex();
1898
1899     TheCondState.CondMet = ExprValue;
1900     TheCondState.Ignore = !TheCondState.CondMet;
1901   }
1902
1903   return false;
1904 }
1905
1906 /// ParseDirectiveElseIf
1907 /// ::= .elseif expression
1908 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1909   if (TheCondState.TheCond != AsmCond::IfCond &&
1910       TheCondState.TheCond != AsmCond::ElseIfCond)
1911       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1912                           " an .elseif");
1913   TheCondState.TheCond = AsmCond::ElseIfCond;
1914
1915   bool LastIgnoreState = false;
1916   if (!TheCondStack.empty())
1917       LastIgnoreState = TheCondStack.back().Ignore;
1918   if (LastIgnoreState || TheCondState.CondMet) {
1919     TheCondState.Ignore = true;
1920     EatToEndOfStatement();
1921   }
1922   else {
1923     int64_t ExprValue;
1924     if (ParseAbsoluteExpression(ExprValue))
1925       return true;
1926
1927     if (getLexer().isNot(AsmToken::EndOfStatement))
1928       return TokError("unexpected token in '.elseif' directive");
1929
1930     Lex();
1931     TheCondState.CondMet = ExprValue;
1932     TheCondState.Ignore = !TheCondState.CondMet;
1933   }
1934
1935   return false;
1936 }
1937
1938 /// ParseDirectiveElse
1939 /// ::= .else
1940 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1941   if (getLexer().isNot(AsmToken::EndOfStatement))
1942     return TokError("unexpected token in '.else' directive");
1943
1944   Lex();
1945
1946   if (TheCondState.TheCond != AsmCond::IfCond &&
1947       TheCondState.TheCond != AsmCond::ElseIfCond)
1948       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1949                           ".elseif");
1950   TheCondState.TheCond = AsmCond::ElseCond;
1951   bool LastIgnoreState = false;
1952   if (!TheCondStack.empty())
1953     LastIgnoreState = TheCondStack.back().Ignore;
1954   if (LastIgnoreState || TheCondState.CondMet)
1955     TheCondState.Ignore = true;
1956   else
1957     TheCondState.Ignore = false;
1958
1959   return false;
1960 }
1961
1962 /// ParseDirectiveEndIf
1963 /// ::= .endif
1964 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1965   if (getLexer().isNot(AsmToken::EndOfStatement))
1966     return TokError("unexpected token in '.endif' directive");
1967
1968   Lex();
1969
1970   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1971       TheCondStack.empty())
1972     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1973                         ".else");
1974   if (!TheCondStack.empty()) {
1975     TheCondState = TheCondStack.back();
1976     TheCondStack.pop_back();
1977   }
1978
1979   return false;
1980 }
1981
1982 /// ParseDirectiveFile
1983 /// ::= .file [number] string
1984 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1985   // FIXME: I'm not sure what this is.
1986   int64_t FileNumber = -1;
1987   SMLoc FileNumberLoc = getLexer().getLoc();
1988   if (getLexer().is(AsmToken::Integer)) {
1989     FileNumber = getTok().getIntVal();
1990     Lex();
1991
1992     if (FileNumber < 1)
1993       return TokError("file number less than one");
1994   }
1995
1996   if (getLexer().isNot(AsmToken::String))
1997     return TokError("unexpected token in '.file' directive");
1998
1999   StringRef Filename = getTok().getString();
2000   Filename = Filename.substr(1, Filename.size()-2);
2001   Lex();
2002
2003   if (getLexer().isNot(AsmToken::EndOfStatement))
2004     return TokError("unexpected token in '.file' directive");
2005
2006   if (FileNumber == -1)
2007     getStreamer().EmitFileDirective(Filename);
2008   else {
2009     if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2010       Error(FileNumberLoc, "file number already allocated");
2011   }
2012
2013   return false;
2014 }
2015
2016 /// ParseDirectiveLine
2017 /// ::= .line [number]
2018 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2019   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2020     if (getLexer().isNot(AsmToken::Integer))
2021       return TokError("unexpected token in '.line' directive");
2022
2023     int64_t LineNumber = getTok().getIntVal();
2024     (void) LineNumber;
2025     Lex();
2026
2027     // FIXME: Do something with the .line.
2028   }
2029
2030   if (getLexer().isNot(AsmToken::EndOfStatement))
2031     return TokError("unexpected token in '.line' directive");
2032
2033   return false;
2034 }
2035
2036
2037 /// ParseDirectiveLoc
2038 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2039 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2040 /// The first number is a file number, must have been previously assigned with
2041 /// a .file directive, the second number is the line number and optionally the
2042 /// third number is a column position (zero if not specified).  The remaining
2043 /// optional items are .loc sub-directives.
2044 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2045
2046   if (getLexer().isNot(AsmToken::Integer))
2047     return TokError("unexpected token in '.loc' directive");
2048   int64_t FileNumber = getTok().getIntVal();
2049   if (FileNumber < 1)
2050     return TokError("file number less than one in '.loc' directive");
2051   if (!getContext().isValidDwarfFileNumber(FileNumber))
2052     return TokError("unassigned file number in '.loc' directive");
2053   Lex();
2054
2055   int64_t LineNumber = 0;
2056   if (getLexer().is(AsmToken::Integer)) {
2057     LineNumber = getTok().getIntVal();
2058     if (LineNumber < 1)
2059       return TokError("line number less than one in '.loc' directive");
2060     Lex();
2061   }
2062
2063   int64_t ColumnPos = 0;
2064   if (getLexer().is(AsmToken::Integer)) {
2065     ColumnPos = getTok().getIntVal();
2066     if (ColumnPos < 0)
2067       return TokError("column position less than zero in '.loc' directive");
2068     Lex();
2069   }
2070
2071   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2072   unsigned Isa = 0;
2073   int64_t Discriminator = 0;
2074   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2075     for (;;) {
2076       if (getLexer().is(AsmToken::EndOfStatement))
2077         break;
2078
2079       StringRef Name;
2080       SMLoc Loc = getTok().getLoc();
2081       if (getParser().ParseIdentifier(Name))
2082         return TokError("unexpected token in '.loc' directive");
2083
2084       if (Name == "basic_block")
2085         Flags |= DWARF2_FLAG_BASIC_BLOCK;
2086       else if (Name == "prologue_end")
2087         Flags |= DWARF2_FLAG_PROLOGUE_END;
2088       else if (Name == "epilogue_begin")
2089         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2090       else if (Name == "is_stmt") {
2091         SMLoc Loc = getTok().getLoc();
2092         const MCExpr *Value;
2093         if (getParser().ParseExpression(Value))
2094           return true;
2095         // The expression must be the constant 0 or 1.
2096         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2097           int Value = MCE->getValue();
2098           if (Value == 0)
2099             Flags &= ~DWARF2_FLAG_IS_STMT;
2100           else if (Value == 1)
2101             Flags |= DWARF2_FLAG_IS_STMT;
2102           else
2103             return Error(Loc, "is_stmt value not 0 or 1");
2104         }
2105         else {
2106           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2107         }
2108       }
2109       else if (Name == "isa") {
2110         SMLoc Loc = getTok().getLoc();
2111         const MCExpr *Value;
2112         if (getParser().ParseExpression(Value))
2113           return true;
2114         // The expression must be a constant greater or equal to 0.
2115         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2116           int Value = MCE->getValue();
2117           if (Value < 0)
2118             return Error(Loc, "isa number less than zero");
2119           Isa = Value;
2120         }
2121         else {
2122           return Error(Loc, "isa number not a constant value");
2123         }
2124       }
2125       else if (Name == "discriminator") {
2126         if (getParser().ParseAbsoluteExpression(Discriminator))
2127           return true;
2128       }
2129       else {
2130         return Error(Loc, "unknown sub-directive in '.loc' directive");
2131       }
2132
2133       if (getLexer().is(AsmToken::EndOfStatement))
2134         break;
2135     }
2136   }
2137
2138   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2139                                       Isa, Discriminator);
2140
2141   return false;
2142 }
2143
2144 /// ParseDirectiveStabs
2145 /// ::= .stabs string, number, number, number
2146 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2147                                            SMLoc DirectiveLoc) {
2148   return TokError("unsupported directive '" + Directive + "'");
2149 }
2150
2151 /// ParseDirectiveCFIStartProc
2152 /// ::= .cfi_startproc
2153 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2154                                                   SMLoc DirectiveLoc) {
2155   return getStreamer().EmitCFIStartProc();
2156 }
2157
2158 /// ParseDirectiveCFIEndProc
2159 /// ::= .cfi_endproc
2160 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2161   return getStreamer().EmitCFIEndProc();
2162 }
2163
2164 /// ParseDirectiveCFIDefCfaOffset
2165 /// ::= .cfi_def_cfa_offset offset
2166 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2167                                                      SMLoc DirectiveLoc) {
2168   int64_t Offset = 0;
2169   if (getParser().ParseAbsoluteExpression(Offset))
2170     return true;
2171
2172   return getStreamer().EmitCFIDefCfaOffset(Offset);
2173 }
2174
2175 /// ParseDirectiveCFIDefCfaRegister
2176 /// ::= .cfi_def_cfa_register register
2177 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2178                                                        SMLoc DirectiveLoc) {
2179   int64_t Register = 0;
2180   if (getParser().ParseAbsoluteExpression(Register))
2181     return true;
2182
2183   return getStreamer().EmitCFIDefCfaRegister(Register);
2184 }
2185
2186 /// ParseDirectiveCFIOffset
2187 /// ::= .cfi_off register, offset
2188 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2189   int64_t Register = 0;
2190   int64_t Offset = 0;
2191   if (getParser().ParseAbsoluteExpression(Register))
2192     return true;
2193
2194   if (getLexer().isNot(AsmToken::Comma))
2195     return TokError("unexpected token in directive");
2196   Lex();
2197
2198   if (getParser().ParseAbsoluteExpression(Offset))
2199     return true;
2200
2201   return getStreamer().EmitCFIOffset(Register, Offset);
2202 }
2203
2204 /// ParseDirectiveCFIPersonalityOrLsda
2205 /// ::= .cfi_personality encoding, [symbol_name]
2206 /// ::= .cfi_lsda encoding, [symbol_name]
2207 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2208                                                     SMLoc DirectiveLoc) {
2209   int64_t Encoding = 0;
2210   if (getParser().ParseAbsoluteExpression(Encoding))
2211     return true;
2212   if (Encoding == 255)
2213     return false;
2214
2215   if (Encoding != 0)
2216     return TokError("unsupported encoding.");
2217
2218   if (getLexer().isNot(AsmToken::Comma))
2219     return TokError("unexpected token in directive");
2220   Lex();
2221
2222   StringRef Name;
2223   if (getParser().ParseIdentifier(Name))
2224     return TokError("expected identifier in directive");
2225
2226   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2227
2228   if (IDVal == ".cfi_personality")
2229     return getStreamer().EmitCFIPersonality(Sym);
2230   else {
2231     assert(IDVal == ".cfi_lsda");
2232     return getStreamer().EmitCFILsda(Sym);
2233   }
2234 }
2235
2236 /// ParseDirectiveMacrosOnOff
2237 /// ::= .macros_on
2238 /// ::= .macros_off
2239 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2240                                                  SMLoc DirectiveLoc) {
2241   if (getLexer().isNot(AsmToken::EndOfStatement))
2242     return Error(getLexer().getLoc(),
2243                  "unexpected token in '" + Directive + "' directive");
2244
2245   getParser().MacrosEnabled = Directive == ".macros_on";
2246
2247   return false;
2248 }
2249
2250 /// ParseDirectiveMacro
2251 /// ::= .macro name
2252 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2253                                            SMLoc DirectiveLoc) {
2254   StringRef Name;
2255   if (getParser().ParseIdentifier(Name))
2256     return TokError("expected identifier in directive");
2257
2258   if (getLexer().isNot(AsmToken::EndOfStatement))
2259     return TokError("unexpected token in '.macro' directive");
2260
2261   // Eat the end of statement.
2262   Lex();
2263
2264   AsmToken EndToken, StartToken = getTok();
2265
2266   // Lex the macro definition.
2267   for (;;) {
2268     // Check whether we have reached the end of the file.
2269     if (getLexer().is(AsmToken::Eof))
2270       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2271
2272     // Otherwise, check whether we have reach the .endmacro.
2273     if (getLexer().is(AsmToken::Identifier) &&
2274         (getTok().getIdentifier() == ".endm" ||
2275          getTok().getIdentifier() == ".endmacro")) {
2276       EndToken = getTok();
2277       Lex();
2278       if (getLexer().isNot(AsmToken::EndOfStatement))
2279         return TokError("unexpected token in '" + EndToken.getIdentifier() +
2280                         "' directive");
2281       break;
2282     }
2283
2284     // Otherwise, scan til the end of the statement.
2285     getParser().EatToEndOfStatement();
2286   }
2287
2288   if (getParser().MacroMap.lookup(Name)) {
2289     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2290   }
2291
2292   const char *BodyStart = StartToken.getLoc().getPointer();
2293   const char *BodyEnd = EndToken.getLoc().getPointer();
2294   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2295   getParser().MacroMap[Name] = new Macro(Name, Body);
2296   return false;
2297 }
2298
2299 /// ParseDirectiveEndMacro
2300 /// ::= .endm
2301 /// ::= .endmacro
2302 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2303                                            SMLoc DirectiveLoc) {
2304   if (getLexer().isNot(AsmToken::EndOfStatement))
2305     return TokError("unexpected token in '" + Directive + "' directive");
2306
2307   // If we are inside a macro instantiation, terminate the current
2308   // instantiation.
2309   if (!getParser().ActiveMacros.empty()) {
2310     getParser().HandleMacroExit();
2311     return false;
2312   }
2313
2314   // Otherwise, this .endmacro is a stray entry in the file; well formed
2315   // .endmacro directives are handled during the macro definition parsing.
2316   return TokError("unexpected '" + Directive + "' in file, "
2317                   "no current macro definition");
2318 }
2319
2320 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2321   getParser().CheckForValidSection();
2322
2323   const MCExpr *Value;
2324
2325   if (getParser().ParseExpression(Value))
2326     return true;
2327
2328   if (getLexer().isNot(AsmToken::EndOfStatement))
2329     return TokError("unexpected token in directive");
2330
2331   if (DirName[1] == 's')
2332     getStreamer().EmitSLEB128Value(Value);
2333   else
2334     getStreamer().EmitULEB128Value(Value);
2335
2336   return false;
2337 }
2338
2339
2340 /// \brief Create an MCAsmParser instance.
2341 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2342                                      MCContext &C, MCStreamer &Out,
2343                                      const MCAsmInfo &MAI) {
2344   return new AsmParser(T, SM, C, Out, MAI);
2345 }