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