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