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