MC/AsmParser: Push the burdon of emitting diagnostics about unmatched
[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/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.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/Compiler.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmParser.h"
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 public:
106   AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
107             const MCAsmInfo &MAI);
108   ~AsmParser();
109
110   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
111
112   void AddDirectiveHandler(MCAsmParserExtension *Object,
113                            StringRef Directive,
114                            DirectiveHandler Handler) {
115     DirectiveMap[Directive] = std::make_pair(Object, Handler);
116   }
117
118 public:
119   /// @name MCAsmParser Interface
120   /// {
121
122   virtual SourceMgr &getSourceManager() { return SrcMgr; }
123   virtual MCAsmLexer &getLexer() { return Lexer; }
124   virtual MCContext &getContext() { return Ctx; }
125   virtual MCStreamer &getStreamer() { return Out; }
126
127   virtual void Warning(SMLoc L, const Twine &Meg);
128   virtual bool Error(SMLoc L, const Twine &Msg);
129
130   const AsmToken &Lex();
131
132   bool ParseExpression(const MCExpr *&Res);
133   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
134   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
135   virtual bool ParseAbsoluteExpression(int64_t &Res);
136
137   /// }
138
139 private:
140   bool ParseStatement();
141
142   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
143   void HandleMacroExit();
144
145   void PrintMacroInstantiations();
146   void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
147     
148   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
149   bool EnterIncludeFile(const std::string &Filename);
150
151   /// \brief Reset the current lexer position to that given by \arg Loc. The
152   /// current token is not set; clients should ensure Lex() is called
153   /// subsequently.
154   void JumpToLoc(SMLoc Loc);
155
156   void EatToEndOfStatement();
157
158   /// \brief Parse up to the end of statement and a return the contents from the
159   /// current token until the end of the statement; the current token on exit
160   /// will be either the EndOfStatement or EOF.
161   StringRef ParseStringToEndOfStatement();
162
163   bool ParseAssignment(StringRef Name);
164
165   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
166   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
167   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
168
169   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
170   /// and set \arg Res to the identifier contents.
171   bool ParseIdentifier(StringRef &Res);
172   
173   // Directive Parsing.
174   bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
175   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
176   bool ParseDirectiveFill(); // ".fill"
177   bool ParseDirectiveSpace(); // ".space"
178   bool ParseDirectiveSet(); // ".set"
179   bool ParseDirectiveOrg(); // ".org"
180   // ".align{,32}", ".p2align{,w,l}"
181   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
182
183   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
184   /// accepts a single symbol (which should be a label or an external).
185   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
186   bool ParseDirectiveELFType(); // ELF specific ".type"
187
188   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
189
190   bool ParseDirectiveAbort(); // ".abort"
191   bool ParseDirectiveInclude(); // ".include"
192
193   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
194   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
195   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
196   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
197
198   /// ParseEscapedString - Parse the current token as a string which may include
199   /// escaped characters and return the string contents.
200   bool ParseEscapedString(std::string &Data);
201 };
202
203 /// \brief Generic implementations of directive handling, etc. which is shared
204 /// (or the default, at least) for all assembler parser.
205 class GenericAsmParser : public MCAsmParserExtension {
206   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
207   void AddDirectiveHandler(StringRef Directive) {
208     getParser().AddDirectiveHandler(this, Directive,
209                                     HandleDirective<GenericAsmParser, Handler>);
210   }
211
212 public:
213   GenericAsmParser() {}
214
215   AsmParser &getParser() {
216     return (AsmParser&) this->MCAsmParserExtension::getParser();
217   }
218
219   virtual void Initialize(MCAsmParser &Parser) {
220     // Call the base implementation.
221     this->MCAsmParserExtension::Initialize(Parser);
222
223     // Debugging directives.
224     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
225     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
226     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
227
228     // Macro directives.
229     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
230       ".macros_on");
231     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
232       ".macros_off");
233     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
234     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
235     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
236   }
237
238   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
239   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
240   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
241
242   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
243   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
244   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
245 };
246
247 }
248
249 namespace llvm {
250
251 extern MCAsmParserExtension *createDarwinAsmParser();
252 extern MCAsmParserExtension *createELFAsmParser();
253
254 }
255
256 enum { DEFAULT_ADDRSPACE = 0 };
257
258 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
259                      MCStreamer &_Out, const MCAsmInfo &_MAI)
260   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
261     GenericParser(new GenericAsmParser), PlatformParser(0),
262     CurBuffer(0), MacrosEnabled(true) {
263   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
264
265   // Initialize the generic parser.
266   GenericParser->Initialize(*this);
267
268   // Initialize the platform / file format parser.
269   //
270   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
271   // created.
272   if (_MAI.hasSubsectionsViaSymbols()) {
273     PlatformParser = createDarwinAsmParser();
274     PlatformParser->Initialize(*this);
275   } else {
276     PlatformParser = createELFAsmParser();
277     PlatformParser->Initialize(*this);
278   }
279 }
280
281 AsmParser::~AsmParser() {
282   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
283
284   // Destroy any macros.
285   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
286          ie = MacroMap.end(); it != ie; ++it)
287     delete it->getValue();
288
289   delete PlatformParser;
290   delete GenericParser;
291 }
292
293 void AsmParser::PrintMacroInstantiations() {
294   // Print the active macro instantiation stack.
295   for (std::vector<MacroInstantiation*>::const_reverse_iterator
296          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
297     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
298                  "note");
299 }
300
301 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
302   PrintMessage(L, Msg.str(), "warning");
303   PrintMacroInstantiations();
304 }
305
306 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
307   PrintMessage(L, Msg.str(), "error");
308   PrintMacroInstantiations();
309   return true;
310 }
311
312 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg, 
313                              const char *Type) const {
314   SrcMgr.PrintMessage(Loc, Msg, Type);
315 }
316                   
317 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
318   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
319   if (NewBuf == -1)
320     return true;
321   
322   CurBuffer = NewBuf;
323   
324   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
325   
326   return false;
327 }
328
329 void AsmParser::JumpToLoc(SMLoc Loc) {
330   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
331   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
332 }
333
334 const AsmToken &AsmParser::Lex() {
335   const AsmToken *tok = &Lexer.Lex();
336   
337   if (tok->is(AsmToken::Eof)) {
338     // If this is the end of an included file, pop the parent file off the
339     // include stack.
340     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
341     if (ParentIncludeLoc != SMLoc()) {
342       JumpToLoc(ParentIncludeLoc);
343       tok = &Lexer.Lex();
344     }
345   }
346     
347   if (tok->is(AsmToken::Error))
348     Error(Lexer.getErrLoc(), Lexer.getErr());
349   
350   return *tok;
351 }
352
353 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
354   // Create the initial section, if requested.
355   //
356   // FIXME: Target hook & command line option for initial section.
357   if (!NoInitialTextSection)
358     Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
359                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
360                                       0, SectionKind::getText()));
361
362   // Prime the lexer.
363   Lex();
364   
365   bool HadError = false;
366   
367   AsmCond StartingCondState = TheCondState;
368
369   // While we have input, parse each statement.
370   while (Lexer.isNot(AsmToken::Eof)) {
371     if (!ParseStatement()) continue;
372   
373     // We had an error, remember it and recover by skipping to the next line.
374     HadError = true;
375     EatToEndOfStatement();
376   }
377
378   if (TheCondState.TheCond != StartingCondState.TheCond ||
379       TheCondState.Ignore != StartingCondState.Ignore)
380     return TokError("unmatched .ifs or .elses");
381
382   // Check to see there are no empty DwarfFile slots.
383   const std::vector<MCDwarfFile *> &MCDwarfFiles =
384     getContext().getMCDwarfFiles();
385   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
386     if (!MCDwarfFiles[i]){
387       TokError("unassigned file number: " + Twine(i) + " for .file directives");
388       HadError = true;
389     }
390   }
391   
392   // Finalize the output stream if there are no errors and if the client wants
393   // us to.
394   if (!HadError && !NoFinalize)  
395     Out.Finish();
396
397   return HadError;
398 }
399
400 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
401 void AsmParser::EatToEndOfStatement() {
402   while (Lexer.isNot(AsmToken::EndOfStatement) &&
403          Lexer.isNot(AsmToken::Eof))
404     Lex();
405   
406   // Eat EOL.
407   if (Lexer.is(AsmToken::EndOfStatement))
408     Lex();
409 }
410
411 StringRef AsmParser::ParseStringToEndOfStatement() {
412   const char *Start = getTok().getLoc().getPointer();
413
414   while (Lexer.isNot(AsmToken::EndOfStatement) &&
415          Lexer.isNot(AsmToken::Eof))
416     Lex();
417
418   const char *End = getTok().getLoc().getPointer();
419   return StringRef(Start, End - Start);
420 }
421
422 /// ParseParenExpr - Parse a paren expression and return it.
423 /// NOTE: This assumes the leading '(' has already been consumed.
424 ///
425 /// parenexpr ::= expr)
426 ///
427 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
428   if (ParseExpression(Res)) return true;
429   if (Lexer.isNot(AsmToken::RParen))
430     return TokError("expected ')' in parentheses expression");
431   EndLoc = Lexer.getLoc();
432   Lex();
433   return false;
434 }
435
436 /// ParsePrimaryExpr - Parse a primary expression and return it.
437 ///  primaryexpr ::= (parenexpr
438 ///  primaryexpr ::= symbol
439 ///  primaryexpr ::= number
440 ///  primaryexpr ::= '.'
441 ///  primaryexpr ::= ~,+,- primaryexpr
442 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
443   switch (Lexer.getKind()) {
444   default:
445     return TokError("unknown token in expression");
446   case AsmToken::Exclaim:
447     Lex(); // Eat the operator.
448     if (ParsePrimaryExpr(Res, EndLoc))
449       return true;
450     Res = MCUnaryExpr::CreateLNot(Res, getContext());
451     return false;
452   case AsmToken::String:
453   case AsmToken::Identifier: {
454     // This is a symbol reference.
455     std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
456     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
457
458     // Mark the symbol as used in an expression.
459     Sym->setUsedInExpr(true);
460
461     // Lookup the symbol variant if used.
462     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
463     if (Split.first.size() != getTok().getIdentifier().size())
464       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
465
466     EndLoc = Lexer.getLoc();
467     Lex(); // Eat identifier.
468
469     // If this is an absolute variable reference, substitute it now to preserve
470     // semantics in the face of reassignment.
471     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
472       if (Variant)
473         return Error(EndLoc, "unexpected modified on variable reference");
474
475       Res = Sym->getVariableValue();
476       return false;
477     }
478
479     // Otherwise create a symbol ref.
480     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
481     return false;
482   }
483   case AsmToken::Integer: {
484     SMLoc Loc = getTok().getLoc();
485     int64_t IntVal = getTok().getIntVal();
486     Res = MCConstantExpr::Create(IntVal, getContext());
487     EndLoc = Lexer.getLoc();
488     Lex(); // Eat token.
489     // Look for 'b' or 'f' following an Integer as a directional label
490     if (Lexer.getKind() == AsmToken::Identifier) {
491       StringRef IDVal = getTok().getString();
492       if (IDVal == "f" || IDVal == "b"){
493         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
494                                                       IDVal == "f" ? 1 : 0);
495         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
496                                       getContext());
497         if(IDVal == "b" && Sym->isUndefined())
498           return Error(Loc, "invalid reference to undefined symbol");
499         EndLoc = Lexer.getLoc();
500         Lex(); // Eat identifier.
501       }
502     }
503     return false;
504   }
505   case AsmToken::Dot: {
506     // This is a '.' reference, which references the current PC.  Emit a
507     // temporary label to the streamer and refer to it.
508     MCSymbol *Sym = Ctx.CreateTempSymbol();
509     Out.EmitLabel(Sym);
510     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
511     EndLoc = Lexer.getLoc();
512     Lex(); // Eat identifier.
513     return false;
514   }
515       
516   case AsmToken::LParen:
517     Lex(); // Eat the '('.
518     return ParseParenExpr(Res, EndLoc);
519   case AsmToken::Minus:
520     Lex(); // Eat the operator.
521     if (ParsePrimaryExpr(Res, EndLoc))
522       return true;
523     Res = MCUnaryExpr::CreateMinus(Res, getContext());
524     return false;
525   case AsmToken::Plus:
526     Lex(); // Eat the operator.
527     if (ParsePrimaryExpr(Res, EndLoc))
528       return true;
529     Res = MCUnaryExpr::CreatePlus(Res, getContext());
530     return false;
531   case AsmToken::Tilde:
532     Lex(); // Eat the operator.
533     if (ParsePrimaryExpr(Res, EndLoc))
534       return true;
535     Res = MCUnaryExpr::CreateNot(Res, getContext());
536     return false;
537   }
538 }
539
540 bool AsmParser::ParseExpression(const MCExpr *&Res) {
541   SMLoc EndLoc;
542   return ParseExpression(Res, EndLoc);
543 }
544
545 /// ParseExpression - Parse an expression and return it.
546 /// 
547 ///  expr ::= expr +,- expr          -> lowest.
548 ///  expr ::= expr |,^,&,! expr      -> middle.
549 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
550 ///  expr ::= primaryexpr
551 ///
552 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
553   // Parse the expression.
554   Res = 0;
555   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
556     return true;
557
558   // Try to constant fold it up front, if possible.
559   int64_t Value;
560   if (Res->EvaluateAsAbsolute(Value))
561     Res = MCConstantExpr::Create(Value, getContext());
562
563   return false;
564 }
565
566 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
567   Res = 0;
568   return ParseParenExpr(Res, EndLoc) ||
569          ParseBinOpRHS(1, Res, EndLoc);
570 }
571
572 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
573   const MCExpr *Expr;
574   
575   SMLoc StartLoc = Lexer.getLoc();
576   if (ParseExpression(Expr))
577     return true;
578
579   if (!Expr->EvaluateAsAbsolute(Res))
580     return Error(StartLoc, "expected absolute expression");
581
582   return false;
583 }
584
585 static unsigned getBinOpPrecedence(AsmToken::TokenKind K, 
586                                    MCBinaryExpr::Opcode &Kind) {
587   switch (K) {
588   default:
589     return 0;    // not a binop.
590
591     // Lowest Precedence: &&, ||
592   case AsmToken::AmpAmp:
593     Kind = MCBinaryExpr::LAnd;
594     return 1;
595   case AsmToken::PipePipe:
596     Kind = MCBinaryExpr::LOr;
597     return 1;
598
599     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
600   case AsmToken::Plus:
601     Kind = MCBinaryExpr::Add;
602     return 2;
603   case AsmToken::Minus:
604     Kind = MCBinaryExpr::Sub;
605     return 2;
606   case AsmToken::EqualEqual:
607     Kind = MCBinaryExpr::EQ;
608     return 2;
609   case AsmToken::ExclaimEqual:
610   case AsmToken::LessGreater:
611     Kind = MCBinaryExpr::NE;
612     return 2;
613   case AsmToken::Less:
614     Kind = MCBinaryExpr::LT;
615     return 2;
616   case AsmToken::LessEqual:
617     Kind = MCBinaryExpr::LTE;
618     return 2;
619   case AsmToken::Greater:
620     Kind = MCBinaryExpr::GT;
621     return 2;
622   case AsmToken::GreaterEqual:
623     Kind = MCBinaryExpr::GTE;
624     return 2;
625
626     // Intermediate Precedence: |, &, ^
627     //
628     // FIXME: gas seems to support '!' as an infix operator?
629   case AsmToken::Pipe:
630     Kind = MCBinaryExpr::Or;
631     return 3;
632   case AsmToken::Caret:
633     Kind = MCBinaryExpr::Xor;
634     return 3;
635   case AsmToken::Amp:
636     Kind = MCBinaryExpr::And;
637     return 3;
638
639     // Highest Precedence: *, /, %, <<, >>
640   case AsmToken::Star:
641     Kind = MCBinaryExpr::Mul;
642     return 4;
643   case AsmToken::Slash:
644     Kind = MCBinaryExpr::Div;
645     return 4;
646   case AsmToken::Percent:
647     Kind = MCBinaryExpr::Mod;
648     return 4;
649   case AsmToken::LessLess:
650     Kind = MCBinaryExpr::Shl;
651     return 4;
652   case AsmToken::GreaterGreater:
653     Kind = MCBinaryExpr::Shr;
654     return 4;
655   }
656 }
657
658
659 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
660 /// Res contains the LHS of the expression on input.
661 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
662                               SMLoc &EndLoc) {
663   while (1) {
664     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
665     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
666     
667     // If the next token is lower precedence than we are allowed to eat, return
668     // successfully with what we ate already.
669     if (TokPrec < Precedence)
670       return false;
671     
672     Lex();
673     
674     // Eat the next primary expression.
675     const MCExpr *RHS;
676     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
677     
678     // If BinOp binds less tightly with RHS than the operator after RHS, let
679     // the pending operator take RHS as its LHS.
680     MCBinaryExpr::Opcode Dummy;
681     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
682     if (TokPrec < NextTokPrec) {
683       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
684     }
685
686     // Merge LHS and RHS according to operator.
687     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
688   }
689 }
690
691   
692   
693   
694 /// ParseStatement:
695 ///   ::= EndOfStatement
696 ///   ::= Label* Directive ...Operands... EndOfStatement
697 ///   ::= Label* Identifier OperandList* EndOfStatement
698 bool AsmParser::ParseStatement() {
699   if (Lexer.is(AsmToken::EndOfStatement)) {
700     Out.AddBlankLine();
701     Lex();
702     return false;
703   }
704
705   // Statements always start with an identifier.
706   AsmToken ID = getTok();
707   SMLoc IDLoc = ID.getLoc();
708   StringRef IDVal;
709   int64_t LocalLabelVal = -1;
710   // GUESS allow an integer followed by a ':' as a directional local label
711   if (Lexer.is(AsmToken::Integer)) {
712     LocalLabelVal = getTok().getIntVal();
713     if (LocalLabelVal < 0) {
714       if (!TheCondState.Ignore)
715         return TokError("unexpected token at start of statement");
716       IDVal = "";
717     }
718     else {
719       IDVal = getTok().getString();
720       Lex(); // Consume the integer token to be used as an identifier token.
721       if (Lexer.getKind() != AsmToken::Colon) {
722         if (!TheCondState.Ignore)
723           return TokError("unexpected token at start of statement");
724       }
725     }
726   }
727   else if (ParseIdentifier(IDVal)) {
728     if (!TheCondState.Ignore)
729       return TokError("unexpected token at start of statement");
730     IDVal = "";
731   }
732
733   // Handle conditional assembly here before checking for skipping.  We
734   // have to do this so that .endif isn't skipped in a ".if 0" block for
735   // example.
736   if (IDVal == ".if")
737     return ParseDirectiveIf(IDLoc);
738   if (IDVal == ".elseif")
739     return ParseDirectiveElseIf(IDLoc);
740   if (IDVal == ".else")
741     return ParseDirectiveElse(IDLoc);
742   if (IDVal == ".endif")
743     return ParseDirectiveEndIf(IDLoc);
744     
745   // If we are in a ".if 0" block, ignore this statement.
746   if (TheCondState.Ignore) {
747     EatToEndOfStatement();
748     return false;
749   }
750   
751   // FIXME: Recurse on local labels?
752
753   // See what kind of statement we have.
754   switch (Lexer.getKind()) {
755   case AsmToken::Colon: {
756     // identifier ':'   -> Label.
757     Lex();
758
759     // Diagnose attempt to use a variable as a label.
760     //
761     // FIXME: Diagnostics. Note the location of the definition as a label.
762     // FIXME: This doesn't diagnose assignment to a symbol which has been
763     // implicitly marked as external.
764     MCSymbol *Sym;
765     if (LocalLabelVal == -1)
766       Sym = getContext().GetOrCreateSymbol(IDVal);
767     else
768       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
769     if (!Sym->isUndefined() || Sym->isVariable())
770       return Error(IDLoc, "invalid symbol redefinition");
771     
772     // Emit the label.
773     Out.EmitLabel(Sym);
774    
775     // Consume any end of statement token, if present, to avoid spurious
776     // AddBlankLine calls().
777     if (Lexer.is(AsmToken::EndOfStatement)) {
778       Lex();
779       if (Lexer.is(AsmToken::Eof))
780         return false;
781     }
782
783     return ParseStatement();
784   }
785
786   case AsmToken::Equal:
787     // identifier '=' ... -> assignment statement
788     Lex();
789
790     return ParseAssignment(IDVal);
791
792   default: // Normal instruction or directive.
793     break;
794   }
795
796   // If macros are enabled, check to see if this is a macro instantiation.
797   if (MacrosEnabled)
798     if (const Macro *M = MacroMap.lookup(IDVal))
799       return HandleMacroEntry(IDVal, IDLoc, M);
800
801   // Otherwise, we have a normal instruction or directive.  
802   if (IDVal[0] == '.') {
803     // Assembler features
804     if (IDVal == ".set")
805       return ParseDirectiveSet();
806
807     // Data directives
808
809     if (IDVal == ".ascii")
810       return ParseDirectiveAscii(false);
811     if (IDVal == ".asciz")
812       return ParseDirectiveAscii(true);
813
814     if (IDVal == ".byte")
815       return ParseDirectiveValue(1);
816     if (IDVal == ".short")
817       return ParseDirectiveValue(2);
818     if (IDVal == ".long")
819       return ParseDirectiveValue(4);
820     if (IDVal == ".quad")
821       return ParseDirectiveValue(8);
822
823     if (IDVal == ".align") {
824       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
825       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
826     }
827     if (IDVal == ".align32") {
828       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
829       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
830     }
831     if (IDVal == ".balign")
832       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
833     if (IDVal == ".balignw")
834       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
835     if (IDVal == ".balignl")
836       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
837     if (IDVal == ".p2align")
838       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
839     if (IDVal == ".p2alignw")
840       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
841     if (IDVal == ".p2alignl")
842       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
843
844     if (IDVal == ".org")
845       return ParseDirectiveOrg();
846
847     if (IDVal == ".fill")
848       return ParseDirectiveFill();
849     if (IDVal == ".space")
850       return ParseDirectiveSpace();
851
852     // Symbol attribute directives
853
854     if (IDVal == ".globl" || IDVal == ".global")
855       return ParseDirectiveSymbolAttribute(MCSA_Global);
856     if (IDVal == ".hidden")
857       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
858     if (IDVal == ".indirect_symbol")
859       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
860     if (IDVal == ".internal")
861       return ParseDirectiveSymbolAttribute(MCSA_Internal);
862     if (IDVal == ".lazy_reference")
863       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
864     if (IDVal == ".no_dead_strip")
865       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
866     if (IDVal == ".private_extern")
867       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
868     if (IDVal == ".protected")
869       return ParseDirectiveSymbolAttribute(MCSA_Protected);
870     if (IDVal == ".reference")
871       return ParseDirectiveSymbolAttribute(MCSA_Reference);
872     if (IDVal == ".type")
873       return ParseDirectiveELFType();
874     if (IDVal == ".weak")
875       return ParseDirectiveSymbolAttribute(MCSA_Weak);
876     if (IDVal == ".weak_definition")
877       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
878     if (IDVal == ".weak_reference")
879       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
880     if (IDVal == ".weak_def_can_be_hidden")
881       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
882
883     if (IDVal == ".comm")
884       return ParseDirectiveComm(/*IsLocal=*/false);
885     if (IDVal == ".lcomm")
886       return ParseDirectiveComm(/*IsLocal=*/true);
887
888     if (IDVal == ".abort")
889       return ParseDirectiveAbort();
890     if (IDVal == ".include")
891       return ParseDirectiveInclude();
892
893     // Look up the handler in the handler table.
894     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
895       DirectiveMap.lookup(IDVal);
896     if (Handler.first)
897       return (*Handler.second)(Handler.first, IDVal, IDLoc);
898
899     // Target hook for parsing target specific directives.
900     if (!getTargetParser().ParseDirective(ID))
901       return false;
902
903     Warning(IDLoc, "ignoring directive for now");
904     EatToEndOfStatement();
905     return false;
906   }
907
908   // Canonicalize the opcode to lower case.
909   SmallString<128> Opcode;
910   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
911     Opcode.push_back(tolower(IDVal[i]));
912   
913   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
914   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
915                                                      ParsedOperands);
916   if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
917     HadError = TokError("unexpected token in argument list");
918
919   // Dump the parsed representation, if requested.
920   if (getShowParsedOperands()) {
921     SmallString<256> Str;
922     raw_svector_ostream OS(Str);
923     OS << "parsed instruction: [";
924     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
925       if (i != 0)
926         OS << ", ";
927       ParsedOperands[i]->dump(OS);
928     }
929     OS << "]";
930
931     PrintMessage(IDLoc, OS.str(), "note");
932   }
933
934   // If parsing succeeded, match the instruction.
935   if (!HadError) {
936     MCInst Inst;
937     if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
938       // Emit the instruction on success.
939       Out.EmitInstruction(Inst);
940     } else
941       HadError = true;
942   }
943
944   // If there was no error, consume the end-of-statement token. Otherwise this
945   // will be done by our caller.
946   if (!HadError)
947     Lex();
948
949   // Free any parsed operands.
950   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
951     delete ParsedOperands[i];
952
953   return HadError;
954 }
955
956 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
957                                    const std::vector<std::vector<AsmToken> > &A)
958   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
959 {
960   // Macro instantiation is lexical, unfortunately. We construct a new buffer
961   // to hold the macro body with substitutions.
962   SmallString<256> Buf;
963   raw_svector_ostream OS(Buf);
964
965   StringRef Body = M->Body;
966   while (!Body.empty()) {
967     // Scan for the next substitution.
968     std::size_t End = Body.size(), Pos = 0;
969     for (; Pos != End; ++Pos) {
970       // Check for a substitution or escape.
971       if (Body[Pos] != '$' || Pos + 1 == End)
972         continue;
973
974       char Next = Body[Pos + 1];
975       if (Next == '$' || Next == 'n' || isdigit(Next))
976         break;
977     }
978
979     // Add the prefix.
980     OS << Body.slice(0, Pos);
981
982     // Check if we reached the end.
983     if (Pos == End)
984       break;
985
986     switch (Body[Pos+1]) {
987        // $$ => $
988     case '$':
989       OS << '$';
990       break;
991
992       // $n => number of arguments
993     case 'n':
994       OS << A.size();
995       break;
996
997        // $[0-9] => argument
998     default: {
999       // Missing arguments are ignored.
1000       unsigned Index = Body[Pos+1] - '0';
1001       if (Index >= A.size())
1002         break;
1003
1004       // Otherwise substitute with the token values, with spaces eliminated.
1005       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1006              ie = A[Index].end(); it != ie; ++it)
1007         OS << it->getString();
1008       break;
1009     }
1010     }
1011
1012     // Update the scan point.
1013     Body = Body.substr(Pos + 2);
1014   }
1015
1016   // We include the .endmacro in the buffer as our queue to exit the macro
1017   // instantiation.
1018   OS << ".endmacro\n";
1019
1020   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1021 }
1022
1023 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1024                                  const Macro *M) {
1025   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1026   // this, although we should protect against infinite loops.
1027   if (ActiveMacros.size() == 20)
1028     return TokError("macros cannot be nested more than 20 levels deep");
1029
1030   // Parse the macro instantiation arguments.
1031   std::vector<std::vector<AsmToken> > MacroArguments;
1032   MacroArguments.push_back(std::vector<AsmToken>());
1033   unsigned ParenLevel = 0;
1034   for (;;) {
1035     if (Lexer.is(AsmToken::Eof))
1036       return TokError("unexpected token in macro instantiation");
1037     if (Lexer.is(AsmToken::EndOfStatement))
1038       break;
1039
1040     // If we aren't inside parentheses and this is a comma, start a new token
1041     // list.
1042     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1043       MacroArguments.push_back(std::vector<AsmToken>());
1044     } else {
1045       // Adjust the current parentheses level.
1046       if (Lexer.is(AsmToken::LParen))
1047         ++ParenLevel;
1048       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1049         --ParenLevel;
1050
1051       // Append the token to the current argument list.
1052       MacroArguments.back().push_back(getTok());
1053     }
1054     Lex();
1055   }
1056
1057   // Create the macro instantiation object and add to the current macro
1058   // instantiation stack.
1059   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1060                                                   getTok().getLoc(),
1061                                                   MacroArguments);
1062   ActiveMacros.push_back(MI);
1063
1064   // Jump to the macro instantiation and prime the lexer.
1065   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1066   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1067   Lex();
1068
1069   return false;
1070 }
1071
1072 void AsmParser::HandleMacroExit() {
1073   // Jump to the EndOfStatement we should return to, and consume it.
1074   JumpToLoc(ActiveMacros.back()->ExitLoc);
1075   Lex();
1076
1077   // Pop the instantiation entry.
1078   delete ActiveMacros.back();
1079   ActiveMacros.pop_back();
1080 }
1081
1082 bool AsmParser::ParseAssignment(StringRef Name) {
1083   // FIXME: Use better location, we should use proper tokens.
1084   SMLoc EqualLoc = Lexer.getLoc();
1085
1086   const MCExpr *Value;
1087   if (ParseExpression(Value))
1088     return true;
1089   
1090   if (Lexer.isNot(AsmToken::EndOfStatement))
1091     return TokError("unexpected token in assignment");
1092
1093   // Eat the end of statement marker.
1094   Lex();
1095
1096   // Validate that the LHS is allowed to be a variable (either it has not been
1097   // used as a symbol, or it is an absolute symbol).
1098   MCSymbol *Sym = getContext().LookupSymbol(Name);
1099   if (Sym) {
1100     // Diagnose assignment to a label.
1101     //
1102     // FIXME: Diagnostics. Note the location of the definition as a label.
1103     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1104     if (Sym->isUndefined() && !Sym->isUsedInExpr())
1105       ; // Allow redefinitions of undefined symbols only used in directives.
1106     else if (!Sym->isUndefined() && !Sym->isAbsolute())
1107       return Error(EqualLoc, "redefinition of '" + Name + "'");
1108     else if (!Sym->isVariable())
1109       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1110     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1111       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1112                    Name + "'");
1113   } else
1114     Sym = getContext().GetOrCreateSymbol(Name);
1115
1116   // FIXME: Handle '.'.
1117
1118   Sym->setUsedInExpr(true);
1119
1120   // Do the assignment.
1121   Out.EmitAssignment(Sym, Value);
1122
1123   return false;
1124 }
1125
1126 /// ParseIdentifier:
1127 ///   ::= identifier
1128 ///   ::= string
1129 bool AsmParser::ParseIdentifier(StringRef &Res) {
1130   if (Lexer.isNot(AsmToken::Identifier) &&
1131       Lexer.isNot(AsmToken::String))
1132     return true;
1133
1134   Res = getTok().getIdentifier();
1135
1136   Lex(); // Consume the identifier token.
1137
1138   return false;
1139 }
1140
1141 /// ParseDirectiveSet:
1142 ///   ::= .set identifier ',' expression
1143 bool AsmParser::ParseDirectiveSet() {
1144   StringRef Name;
1145
1146   if (ParseIdentifier(Name))
1147     return TokError("expected identifier after '.set' directive");
1148   
1149   if (getLexer().isNot(AsmToken::Comma))
1150     return TokError("unexpected token in '.set'");
1151   Lex();
1152
1153   return ParseAssignment(Name);
1154 }
1155
1156 bool AsmParser::ParseEscapedString(std::string &Data) {
1157   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1158
1159   Data = "";
1160   StringRef Str = getTok().getStringContents();
1161   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1162     if (Str[i] != '\\') {
1163       Data += Str[i];
1164       continue;
1165     }
1166
1167     // Recognize escaped characters. Note that this escape semantics currently
1168     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1169     ++i;
1170     if (i == e)
1171       return TokError("unexpected backslash at end of string");
1172
1173     // Recognize octal sequences.
1174     if ((unsigned) (Str[i] - '0') <= 7) {
1175       // Consume up to three octal characters.
1176       unsigned Value = Str[i] - '0';
1177
1178       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1179         ++i;
1180         Value = Value * 8 + (Str[i] - '0');
1181
1182         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1183           ++i;
1184           Value = Value * 8 + (Str[i] - '0');
1185         }
1186       }
1187
1188       if (Value > 255)
1189         return TokError("invalid octal escape sequence (out of range)");
1190
1191       Data += (unsigned char) Value;
1192       continue;
1193     }
1194
1195     // Otherwise recognize individual escapes.
1196     switch (Str[i]) {
1197     default:
1198       // Just reject invalid escape sequences for now.
1199       return TokError("invalid escape sequence (unrecognized character)");
1200
1201     case 'b': Data += '\b'; break;
1202     case 'f': Data += '\f'; break;
1203     case 'n': Data += '\n'; break;
1204     case 'r': Data += '\r'; break;
1205     case 't': Data += '\t'; break;
1206     case '"': Data += '"'; break;
1207     case '\\': Data += '\\'; break;
1208     }
1209   }
1210
1211   return false;
1212 }
1213
1214 /// ParseDirectiveAscii:
1215 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1216 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1217   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1218     for (;;) {
1219       if (getLexer().isNot(AsmToken::String))
1220         return TokError("expected string in '.ascii' or '.asciz' directive");
1221
1222       std::string Data;
1223       if (ParseEscapedString(Data))
1224         return true;
1225
1226       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1227       if (ZeroTerminated)
1228         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1229
1230       Lex();
1231
1232       if (getLexer().is(AsmToken::EndOfStatement))
1233         break;
1234
1235       if (getLexer().isNot(AsmToken::Comma))
1236         return TokError("unexpected token in '.ascii' or '.asciz' directive");
1237       Lex();
1238     }
1239   }
1240
1241   Lex();
1242   return false;
1243 }
1244
1245 /// ParseDirectiveValue
1246 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1247 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1248   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1249     for (;;) {
1250       const MCExpr *Value;
1251       SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1252       if (ParseExpression(Value))
1253         return true;
1254
1255       // Special case constant expressions to match code generator.
1256       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1257         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1258       else
1259         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1260
1261       if (getLexer().is(AsmToken::EndOfStatement))
1262         break;
1263       
1264       // FIXME: Improve diagnostic.
1265       if (getLexer().isNot(AsmToken::Comma))
1266         return TokError("unexpected token in directive");
1267       Lex();
1268     }
1269   }
1270
1271   Lex();
1272   return false;
1273 }
1274
1275 /// ParseDirectiveSpace
1276 ///  ::= .space expression [ , expression ]
1277 bool AsmParser::ParseDirectiveSpace() {
1278   int64_t NumBytes;
1279   if (ParseAbsoluteExpression(NumBytes))
1280     return true;
1281
1282   int64_t FillExpr = 0;
1283   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1284     if (getLexer().isNot(AsmToken::Comma))
1285       return TokError("unexpected token in '.space' directive");
1286     Lex();
1287     
1288     if (ParseAbsoluteExpression(FillExpr))
1289       return true;
1290
1291     if (getLexer().isNot(AsmToken::EndOfStatement))
1292       return TokError("unexpected token in '.space' directive");
1293   }
1294
1295   Lex();
1296
1297   if (NumBytes <= 0)
1298     return TokError("invalid number of bytes in '.space' directive");
1299
1300   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1301   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1302
1303   return false;
1304 }
1305
1306 /// ParseDirectiveFill
1307 ///  ::= .fill expression , expression , expression
1308 bool AsmParser::ParseDirectiveFill() {
1309   int64_t NumValues;
1310   if (ParseAbsoluteExpression(NumValues))
1311     return true;
1312
1313   if (getLexer().isNot(AsmToken::Comma))
1314     return TokError("unexpected token in '.fill' directive");
1315   Lex();
1316   
1317   int64_t FillSize;
1318   if (ParseAbsoluteExpression(FillSize))
1319     return true;
1320
1321   if (getLexer().isNot(AsmToken::Comma))
1322     return TokError("unexpected token in '.fill' directive");
1323   Lex();
1324   
1325   int64_t FillExpr;
1326   if (ParseAbsoluteExpression(FillExpr))
1327     return true;
1328
1329   if (getLexer().isNot(AsmToken::EndOfStatement))
1330     return TokError("unexpected token in '.fill' directive");
1331   
1332   Lex();
1333
1334   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1335     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1336
1337   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1338     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1339
1340   return false;
1341 }
1342
1343 /// ParseDirectiveOrg
1344 ///  ::= .org expression [ , expression ]
1345 bool AsmParser::ParseDirectiveOrg() {
1346   const MCExpr *Offset;
1347   if (ParseExpression(Offset))
1348     return true;
1349
1350   // Parse optional fill expression.
1351   int64_t FillExpr = 0;
1352   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1353     if (getLexer().isNot(AsmToken::Comma))
1354       return TokError("unexpected token in '.org' directive");
1355     Lex();
1356     
1357     if (ParseAbsoluteExpression(FillExpr))
1358       return true;
1359
1360     if (getLexer().isNot(AsmToken::EndOfStatement))
1361       return TokError("unexpected token in '.org' directive");
1362   }
1363
1364   Lex();
1365
1366   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1367   // has to be relative to the current section.
1368   getStreamer().EmitValueToOffset(Offset, FillExpr);
1369
1370   return false;
1371 }
1372
1373 /// ParseDirectiveAlign
1374 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1375 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1376   SMLoc AlignmentLoc = getLexer().getLoc();
1377   int64_t Alignment;
1378   if (ParseAbsoluteExpression(Alignment))
1379     return true;
1380
1381   SMLoc MaxBytesLoc;
1382   bool HasFillExpr = false;
1383   int64_t FillExpr = 0;
1384   int64_t MaxBytesToFill = 0;
1385   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1386     if (getLexer().isNot(AsmToken::Comma))
1387       return TokError("unexpected token in directive");
1388     Lex();
1389
1390     // The fill expression can be omitted while specifying a maximum number of
1391     // alignment bytes, e.g:
1392     //  .align 3,,4
1393     if (getLexer().isNot(AsmToken::Comma)) {
1394       HasFillExpr = true;
1395       if (ParseAbsoluteExpression(FillExpr))
1396         return true;
1397     }
1398
1399     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1400       if (getLexer().isNot(AsmToken::Comma))
1401         return TokError("unexpected token in directive");
1402       Lex();
1403
1404       MaxBytesLoc = getLexer().getLoc();
1405       if (ParseAbsoluteExpression(MaxBytesToFill))
1406         return true;
1407       
1408       if (getLexer().isNot(AsmToken::EndOfStatement))
1409         return TokError("unexpected token in directive");
1410     }
1411   }
1412
1413   Lex();
1414
1415   if (!HasFillExpr)
1416     FillExpr = 0;
1417
1418   // Compute alignment in bytes.
1419   if (IsPow2) {
1420     // FIXME: Diagnose overflow.
1421     if (Alignment >= 32) {
1422       Error(AlignmentLoc, "invalid alignment value");
1423       Alignment = 31;
1424     }
1425
1426     Alignment = 1ULL << Alignment;
1427   }
1428
1429   // Diagnose non-sensical max bytes to align.
1430   if (MaxBytesLoc.isValid()) {
1431     if (MaxBytesToFill < 1) {
1432       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1433             "many bytes, ignoring maximum bytes expression");
1434       MaxBytesToFill = 0;
1435     }
1436
1437     if (MaxBytesToFill >= Alignment) {
1438       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1439               "has no effect");
1440       MaxBytesToFill = 0;
1441     }
1442   }
1443
1444   // Check whether we should use optimal code alignment for this .align
1445   // directive.
1446   //
1447   // FIXME: This should be using a target hook.
1448   bool UseCodeAlign = false;
1449   if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1450         getStreamer().getCurrentSection()))
1451     UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1452   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1453       ValueSize == 1 && UseCodeAlign) {
1454     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1455   } else {
1456     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1457     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1458                                        MaxBytesToFill);
1459   }
1460
1461   return false;
1462 }
1463
1464 /// ParseDirectiveSymbolAttribute
1465 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1466 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1467   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1468     for (;;) {
1469       StringRef Name;
1470
1471       if (ParseIdentifier(Name))
1472         return TokError("expected identifier in directive");
1473       
1474       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1475
1476       getStreamer().EmitSymbolAttribute(Sym, Attr);
1477
1478       if (getLexer().is(AsmToken::EndOfStatement))
1479         break;
1480
1481       if (getLexer().isNot(AsmToken::Comma))
1482         return TokError("unexpected token in directive");
1483       Lex();
1484     }
1485   }
1486
1487   Lex();
1488   return false;  
1489 }
1490
1491 /// ParseDirectiveELFType
1492 ///  ::= .type identifier , @attribute
1493 bool AsmParser::ParseDirectiveELFType() {
1494   StringRef Name;
1495   if (ParseIdentifier(Name))
1496     return TokError("expected identifier in directive");
1497
1498   // Handle the identifier as the key symbol.
1499   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1500
1501   if (getLexer().isNot(AsmToken::Comma))
1502     return TokError("unexpected token in '.type' directive");
1503   Lex();
1504
1505   if (getLexer().isNot(AsmToken::At))
1506     return TokError("expected '@' before type");
1507   Lex();
1508
1509   StringRef Type;
1510   SMLoc TypeLoc;
1511
1512   TypeLoc = getLexer().getLoc();
1513   if (ParseIdentifier(Type))
1514     return TokError("expected symbol type in directive");
1515
1516   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1517     .Case("function", MCSA_ELF_TypeFunction)
1518     .Case("object", MCSA_ELF_TypeObject)
1519     .Case("tls_object", MCSA_ELF_TypeTLS)
1520     .Case("common", MCSA_ELF_TypeCommon)
1521     .Case("notype", MCSA_ELF_TypeNoType)
1522     .Default(MCSA_Invalid);
1523
1524   if (Attr == MCSA_Invalid)
1525     return Error(TypeLoc, "unsupported attribute in '.type' directive");
1526
1527   if (getLexer().isNot(AsmToken::EndOfStatement))
1528     return TokError("unexpected token in '.type' directive");
1529
1530   Lex();
1531
1532   getStreamer().EmitSymbolAttribute(Sym, Attr);
1533
1534   return false;
1535 }
1536
1537 /// ParseDirectiveComm
1538 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1539 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1540   SMLoc IDLoc = getLexer().getLoc();
1541   StringRef Name;
1542   if (ParseIdentifier(Name))
1543     return TokError("expected identifier in directive");
1544   
1545   // Handle the identifier as the key symbol.
1546   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1547
1548   if (getLexer().isNot(AsmToken::Comma))
1549     return TokError("unexpected token in directive");
1550   Lex();
1551
1552   int64_t Size;
1553   SMLoc SizeLoc = getLexer().getLoc();
1554   if (ParseAbsoluteExpression(Size))
1555     return true;
1556
1557   int64_t Pow2Alignment = 0;
1558   SMLoc Pow2AlignmentLoc;
1559   if (getLexer().is(AsmToken::Comma)) {
1560     Lex();
1561     Pow2AlignmentLoc = getLexer().getLoc();
1562     if (ParseAbsoluteExpression(Pow2Alignment))
1563       return true;
1564     
1565     // If this target takes alignments in bytes (not log) validate and convert.
1566     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1567       if (!isPowerOf2_64(Pow2Alignment))
1568         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1569       Pow2Alignment = Log2_64(Pow2Alignment);
1570     }
1571   }
1572   
1573   if (getLexer().isNot(AsmToken::EndOfStatement))
1574     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1575   
1576   Lex();
1577
1578   // NOTE: a size of zero for a .comm should create a undefined symbol
1579   // but a size of .lcomm creates a bss symbol of size zero.
1580   if (Size < 0)
1581     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1582                  "be less than zero");
1583
1584   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1585   // may internally end up wanting an alignment in bytes.
1586   // FIXME: Diagnose overflow.
1587   if (Pow2Alignment < 0)
1588     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1589                  "alignment, can't be less than zero");
1590
1591   if (!Sym->isUndefined())
1592     return Error(IDLoc, "invalid symbol redefinition");
1593
1594   // '.lcomm' is equivalent to '.zerofill'.
1595   // Create the Symbol as a common or local common with Size and Pow2Alignment
1596   if (IsLocal) {
1597     getStreamer().EmitZerofill(Ctx.getMachOSection(
1598                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1599                                  0, SectionKind::getBSS()),
1600                                Sym, Size, 1 << Pow2Alignment);
1601     return false;
1602   }
1603
1604   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1605   return false;
1606 }
1607
1608 /// ParseDirectiveAbort
1609 ///  ::= .abort [... message ...]
1610 bool AsmParser::ParseDirectiveAbort() {
1611   // FIXME: Use loc from directive.
1612   SMLoc Loc = getLexer().getLoc();
1613
1614   StringRef Str = ParseStringToEndOfStatement();
1615   if (getLexer().isNot(AsmToken::EndOfStatement))
1616     return TokError("unexpected token in '.abort' directive");
1617
1618   Lex();
1619
1620   if (Str.empty())
1621     Error(Loc, ".abort detected. Assembly stopping.");
1622   else
1623     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1624   // FIXME: Actually abort assembly here.
1625
1626   return false;
1627 }
1628
1629 /// ParseDirectiveInclude
1630 ///  ::= .include "filename"
1631 bool AsmParser::ParseDirectiveInclude() {
1632   if (getLexer().isNot(AsmToken::String))
1633     return TokError("expected string in '.include' directive");
1634   
1635   std::string Filename = getTok().getString();
1636   SMLoc IncludeLoc = getLexer().getLoc();
1637   Lex();
1638
1639   if (getLexer().isNot(AsmToken::EndOfStatement))
1640     return TokError("unexpected token in '.include' directive");
1641   
1642   // Strip the quotes.
1643   Filename = Filename.substr(1, Filename.size()-2);
1644   
1645   // Attempt to switch the lexer to the included file before consuming the end
1646   // of statement to avoid losing it when we switch.
1647   if (EnterIncludeFile(Filename)) {
1648     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1649     return true;
1650   }
1651
1652   return false;
1653 }
1654
1655 /// ParseDirectiveIf
1656 /// ::= .if expression
1657 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1658   TheCondStack.push_back(TheCondState);
1659   TheCondState.TheCond = AsmCond::IfCond;
1660   if(TheCondState.Ignore) {
1661     EatToEndOfStatement();
1662   }
1663   else {
1664     int64_t ExprValue;
1665     if (ParseAbsoluteExpression(ExprValue))
1666       return true;
1667
1668     if (getLexer().isNot(AsmToken::EndOfStatement))
1669       return TokError("unexpected token in '.if' directive");
1670     
1671     Lex();
1672
1673     TheCondState.CondMet = ExprValue;
1674     TheCondState.Ignore = !TheCondState.CondMet;
1675   }
1676
1677   return false;
1678 }
1679
1680 /// ParseDirectiveElseIf
1681 /// ::= .elseif expression
1682 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1683   if (TheCondState.TheCond != AsmCond::IfCond &&
1684       TheCondState.TheCond != AsmCond::ElseIfCond)
1685       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1686                           " an .elseif");
1687   TheCondState.TheCond = AsmCond::ElseIfCond;
1688
1689   bool LastIgnoreState = false;
1690   if (!TheCondStack.empty())
1691       LastIgnoreState = TheCondStack.back().Ignore;
1692   if (LastIgnoreState || TheCondState.CondMet) {
1693     TheCondState.Ignore = true;
1694     EatToEndOfStatement();
1695   }
1696   else {
1697     int64_t ExprValue;
1698     if (ParseAbsoluteExpression(ExprValue))
1699       return true;
1700
1701     if (getLexer().isNot(AsmToken::EndOfStatement))
1702       return TokError("unexpected token in '.elseif' directive");
1703     
1704     Lex();
1705     TheCondState.CondMet = ExprValue;
1706     TheCondState.Ignore = !TheCondState.CondMet;
1707   }
1708
1709   return false;
1710 }
1711
1712 /// ParseDirectiveElse
1713 /// ::= .else
1714 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1715   if (getLexer().isNot(AsmToken::EndOfStatement))
1716     return TokError("unexpected token in '.else' directive");
1717   
1718   Lex();
1719
1720   if (TheCondState.TheCond != AsmCond::IfCond &&
1721       TheCondState.TheCond != AsmCond::ElseIfCond)
1722       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1723                           ".elseif");
1724   TheCondState.TheCond = AsmCond::ElseCond;
1725   bool LastIgnoreState = false;
1726   if (!TheCondStack.empty())
1727     LastIgnoreState = TheCondStack.back().Ignore;
1728   if (LastIgnoreState || TheCondState.CondMet)
1729     TheCondState.Ignore = true;
1730   else
1731     TheCondState.Ignore = false;
1732
1733   return false;
1734 }
1735
1736 /// ParseDirectiveEndIf
1737 /// ::= .endif
1738 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1739   if (getLexer().isNot(AsmToken::EndOfStatement))
1740     return TokError("unexpected token in '.endif' directive");
1741   
1742   Lex();
1743
1744   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1745       TheCondStack.empty())
1746     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1747                         ".else");
1748   if (!TheCondStack.empty()) {
1749     TheCondState = TheCondStack.back();
1750     TheCondStack.pop_back();
1751   }
1752
1753   return false;
1754 }
1755
1756 /// ParseDirectiveFile
1757 /// ::= .file [number] string
1758 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1759   // FIXME: I'm not sure what this is.
1760   int64_t FileNumber = -1;
1761   SMLoc FileNumberLoc = getLexer().getLoc();
1762   if (getLexer().is(AsmToken::Integer)) {
1763     FileNumber = getTok().getIntVal();
1764     Lex();
1765
1766     if (FileNumber < 1)
1767       return TokError("file number less than one");
1768   }
1769
1770   if (getLexer().isNot(AsmToken::String))
1771     return TokError("unexpected token in '.file' directive");
1772
1773   StringRef Filename = getTok().getString();
1774   Filename = Filename.substr(1, Filename.size()-2);
1775   Lex();
1776
1777   if (getLexer().isNot(AsmToken::EndOfStatement))
1778     return TokError("unexpected token in '.file' directive");
1779
1780   if (FileNumber == -1)
1781     getStreamer().EmitFileDirective(Filename);
1782   else {
1783      if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1784         Error(FileNumberLoc, "file number already allocated");
1785     getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1786   }
1787
1788   return false;
1789 }
1790
1791 /// ParseDirectiveLine
1792 /// ::= .line [number]
1793 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1794   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1795     if (getLexer().isNot(AsmToken::Integer))
1796       return TokError("unexpected token in '.line' directive");
1797
1798     int64_t LineNumber = getTok().getIntVal();
1799     (void) LineNumber;
1800     Lex();
1801
1802     // FIXME: Do something with the .line.
1803   }
1804
1805   if (getLexer().isNot(AsmToken::EndOfStatement))
1806     return TokError("unexpected token in '.line' directive");
1807
1808   return false;
1809 }
1810
1811
1812 /// ParseDirectiveLoc
1813 /// ::= .loc number [number [number]]
1814 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1815   if (getLexer().isNot(AsmToken::Integer))
1816     return TokError("unexpected token in '.loc' directive");
1817
1818   // FIXME: What are these fields?
1819   int64_t FileNumber = getTok().getIntVal();
1820   (void) FileNumber;
1821   // FIXME: Validate file.
1822
1823   Lex();
1824   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1825     if (getLexer().isNot(AsmToken::Integer))
1826       return TokError("unexpected token in '.loc' directive");
1827
1828     int64_t Param2 = getTok().getIntVal();
1829     (void) Param2;
1830     Lex();
1831
1832     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1833       if (getLexer().isNot(AsmToken::Integer))
1834         return TokError("unexpected token in '.loc' directive");
1835
1836       int64_t Param3 = getTok().getIntVal();
1837       (void) Param3;
1838       Lex();
1839
1840       // FIXME: Do something with the .loc.
1841     }
1842   }
1843
1844   if (getLexer().isNot(AsmToken::EndOfStatement))
1845     return TokError("unexpected token in '.file' directive");
1846
1847   return false;
1848 }
1849
1850 /// ParseDirectiveMacrosOnOff
1851 /// ::= .macros_on
1852 /// ::= .macros_off
1853 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1854                                                  SMLoc DirectiveLoc) {
1855   if (getLexer().isNot(AsmToken::EndOfStatement))
1856     return Error(getLexer().getLoc(),
1857                  "unexpected token in '" + Directive + "' directive");
1858
1859   getParser().MacrosEnabled = Directive == ".macros_on";
1860
1861   return false;
1862 }
1863
1864 /// ParseDirectiveMacro
1865 /// ::= .macro name
1866 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1867                                            SMLoc DirectiveLoc) {
1868   StringRef Name;
1869   if (getParser().ParseIdentifier(Name))
1870     return TokError("expected identifier in directive");
1871
1872   if (getLexer().isNot(AsmToken::EndOfStatement))
1873     return TokError("unexpected token in '.macro' directive");
1874
1875   // Eat the end of statement.
1876   Lex();
1877
1878   AsmToken EndToken, StartToken = getTok();
1879
1880   // Lex the macro definition.
1881   for (;;) {
1882     // Check whether we have reached the end of the file.
1883     if (getLexer().is(AsmToken::Eof))
1884       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1885
1886     // Otherwise, check whether we have reach the .endmacro.
1887     if (getLexer().is(AsmToken::Identifier) &&
1888         (getTok().getIdentifier() == ".endm" ||
1889          getTok().getIdentifier() == ".endmacro")) {
1890       EndToken = getTok();
1891       Lex();
1892       if (getLexer().isNot(AsmToken::EndOfStatement))
1893         return TokError("unexpected token in '" + EndToken.getIdentifier() +
1894                         "' directive");
1895       break;
1896     }
1897
1898     // Otherwise, scan til the end of the statement.
1899     getParser().EatToEndOfStatement();
1900   }
1901
1902   if (getParser().MacroMap.lookup(Name)) {
1903     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1904   }
1905
1906   const char *BodyStart = StartToken.getLoc().getPointer();
1907   const char *BodyEnd = EndToken.getLoc().getPointer();
1908   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1909   getParser().MacroMap[Name] = new Macro(Name, Body);
1910   return false;
1911 }
1912
1913 /// ParseDirectiveEndMacro
1914 /// ::= .endm
1915 /// ::= .endmacro
1916 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1917                                            SMLoc DirectiveLoc) {
1918   if (getLexer().isNot(AsmToken::EndOfStatement))
1919     return TokError("unexpected token in '" + Directive + "' directive");
1920
1921   // If we are inside a macro instantiation, terminate the current
1922   // instantiation.
1923   if (!getParser().ActiveMacros.empty()) {
1924     getParser().HandleMacroExit();
1925     return false;
1926   }
1927
1928   // Otherwise, this .endmacro is a stray entry in the file; well formed
1929   // .endmacro directives are handled during the macro definition parsing.
1930   return TokError("unexpected '" + Directive + "' in file, "
1931                   "no current macro definition");
1932 }
1933
1934 /// \brief Create an MCAsmParser instance.
1935 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1936                                      MCContext &C, MCStreamer &Out,
1937                                      const MCAsmInfo &MAI) {
1938   return new AsmParser(T, SM, C, Out, MAI);
1939 }