]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/lib/MC/MCParser/AsmParser.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / 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/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cctype>
40 #include <set>
41 #include <string>
42 #include <vector>
43 using namespace llvm;
44
45 static cl::opt<bool>
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47                        cl::desc("Consider warnings as error"));
48
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {} 
50
51 namespace {
52
53 /// \brief Helper class for tracking macro definitions.
54 typedef std::vector<AsmToken> MacroArgument;
55 typedef std::vector<MacroArgument> MacroArguments;
56 typedef std::pair<StringRef, MacroArgument> MacroParameter;
57 typedef std::vector<MacroParameter> MacroParameters;
58
59 struct Macro {
60   StringRef Name;
61   StringRef Body;
62   MacroParameters Parameters;
63
64 public:
65   Macro(StringRef N, StringRef B, const MacroParameters &P) :
66     Name(N), Body(B), Parameters(P) {}
67 };
68
69 /// \brief Helper class for storing information about an active macro
70 /// instantiation.
71 struct MacroInstantiation {
72   /// The macro being instantiated.
73   const Macro *TheMacro;
74
75   /// The macro instantiation with substitutions.
76   MemoryBuffer *Instantiation;
77
78   /// The location of the instantiation.
79   SMLoc InstantiationLoc;
80
81   /// The location where parsing should resume upon instantiation completion.
82   SMLoc ExitLoc;
83
84 public:
85   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
86                      MemoryBuffer *I);
87 };
88
89 //struct AsmRewrite;
90 struct ParseStatementInfo {
91   /// ParsedOperands - The parsed operands from the last parsed statement.
92   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
93
94   /// Opcode - The opcode from the last parsed instruction.
95   unsigned Opcode;
96
97   SmallVectorImpl<AsmRewrite> *AsmRewrites;
98
99   ParseStatementInfo() : Opcode(~0U), AsmRewrites(0) {}
100   ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
101     : Opcode(~0), AsmRewrites(rewrites) {}
102
103   ~ParseStatementInfo() {
104     // Free any parsed operands.
105     for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
106       delete ParsedOperands[i];
107     ParsedOperands.clear();
108   }
109 };
110
111 /// \brief The concrete assembly parser instance.
112 class AsmParser : public MCAsmParser {
113   friend class GenericAsmParser;
114
115   AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
116   void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
117 private:
118   AsmLexer Lexer;
119   MCContext &Ctx;
120   MCStreamer &Out;
121   const MCAsmInfo &MAI;
122   SourceMgr &SrcMgr;
123   SourceMgr::DiagHandlerTy SavedDiagHandler;
124   void *SavedDiagContext;
125   MCAsmParserExtension *GenericParser;
126   MCAsmParserExtension *PlatformParser;
127
128   /// This is the current buffer index we're lexing from as managed by the
129   /// SourceMgr object.
130   int CurBuffer;
131
132   AsmCond TheCondState;
133   std::vector<AsmCond> TheCondStack;
134
135   /// DirectiveMap - This is a table handlers for directives.  Each handler is
136   /// invoked after the directive identifier is read and is responsible for
137   /// parsing and validating the rest of the directive.  The handler is passed
138   /// in the directive name and the location of the directive keyword.
139   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
140
141   /// MacroMap - Map of currently defined macros.
142   StringMap<Macro*> MacroMap;
143
144   /// ActiveMacros - Stack of active macro instantiations.
145   std::vector<MacroInstantiation*> ActiveMacros;
146
147   /// Boolean tracking whether macro substitution is enabled.
148   unsigned MacrosEnabled : 1;
149
150   /// Flag tracking whether any errors have been encountered.
151   unsigned HadError : 1;
152
153   /// The values from the last parsed cpp hash file line comment if any.
154   StringRef CppHashFilename;
155   int64_t CppHashLineNumber;
156   SMLoc CppHashLoc;
157   int CppHashBuf;
158
159   /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
160   unsigned AssemblerDialect;
161
162   /// IsDarwin - is Darwin compatibility enabled?
163   bool IsDarwin;
164
165   /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
166   bool ParsingInlineAsm;
167
168 public:
169   AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
170             const MCAsmInfo &MAI);
171   virtual ~AsmParser();
172
173   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
174
175   virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
176                                    StringRef Directive,
177                                    DirectiveHandler Handler) {
178     DirectiveMap[Directive] = std::make_pair(Object, Handler);
179   }
180
181 public:
182   /// @name MCAsmParser Interface
183   /// {
184
185   virtual SourceMgr &getSourceManager() { return SrcMgr; }
186   virtual MCAsmLexer &getLexer() { return Lexer; }
187   virtual MCContext &getContext() { return Ctx; }
188   virtual MCStreamer &getStreamer() { return Out; }
189   virtual unsigned getAssemblerDialect() { 
190     if (AssemblerDialect == ~0U)
191       return MAI.getAssemblerDialect(); 
192     else
193       return AssemblerDialect;
194   }
195   virtual void setAssemblerDialect(unsigned i) {
196     AssemblerDialect = i;
197   }
198
199   virtual bool Warning(SMLoc L, const Twine &Msg,
200                        ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
201   virtual bool Error(SMLoc L, const Twine &Msg,
202                      ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
203
204   virtual const AsmToken &Lex();
205
206   void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
207   bool isParsingInlineAsm() { return ParsingInlineAsm; }
208
209   bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
210                         unsigned &NumOutputs, unsigned &NumInputs,
211                         SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
212                         SmallVectorImpl<std::string> &Constraints,
213                         SmallVectorImpl<std::string> &Clobbers,
214                         const MCInstrInfo *MII,
215                         const MCInstPrinter *IP,
216                         MCAsmParserSemaCallback &SI);
217
218   bool ParseExpression(const MCExpr *&Res);
219   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
220   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
221   virtual bool ParseAbsoluteExpression(int64_t &Res);
222
223   /// }
224
225 private:
226   void CheckForValidSection();
227
228   bool ParseStatement(ParseStatementInfo &Info);
229   void EatToEndOfLine();
230   bool ParseCppHashLineFilenameComment(const SMLoc &L);
231
232   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
233   bool expandMacro(raw_svector_ostream &OS, StringRef Body,
234                    const MacroParameters &Parameters,
235                    const MacroArguments &A,
236                    const SMLoc &L);
237   void HandleMacroExit();
238
239   void PrintMacroInstantiations();
240   void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
241                     ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
242     SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
243   }
244   static void DiagHandler(const SMDiagnostic &Diag, void *Context);
245
246   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
247   bool EnterIncludeFile(const std::string &Filename);
248   /// ProcessIncbinFile - Process the specified file for the .incbin directive.
249   /// This returns true on failure.
250   bool ProcessIncbinFile(const std::string &Filename);
251
252   /// \brief Reset the current lexer position to that given by \p Loc. The
253   /// current token is not set; clients should ensure Lex() is called
254   /// subsequently.
255   void JumpToLoc(SMLoc Loc);
256
257   virtual void EatToEndOfStatement();
258
259   bool ParseMacroArgument(MacroArgument &MA,
260                           AsmToken::TokenKind &ArgumentDelimiter);
261   bool ParseMacroArguments(const Macro *M, MacroArguments &A);
262
263   /// \brief Parse up to the end of statement and a return the contents from the
264   /// current token until the end of the statement; the current token on exit
265   /// will be either the EndOfStatement or EOF.
266   virtual StringRef ParseStringToEndOfStatement();
267
268   /// \brief Parse until the end of a statement or a comma is encountered,
269   /// return the contents from the current token up to the end or comma.
270   StringRef ParseStringToComma();
271
272   bool ParseAssignment(StringRef Name, bool allow_redef,
273                        bool NoDeadStrip = false);
274
275   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
276   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
277   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
278   bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
279
280   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
281   /// and set \p Res to the identifier contents.
282   virtual bool ParseIdentifier(StringRef &Res);
283
284   // Directive Parsing.
285
286  // ".ascii", ".asciiz", ".string"
287   bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
288   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
289   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
290   bool ParseDirectiveFill(); // ".fill"
291   bool ParseDirectiveSpace(); // ".space"
292   bool ParseDirectiveZero(); // ".zero"
293   bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
294   bool ParseDirectiveOrg(); // ".org"
295   // ".align{,32}", ".p2align{,w,l}"
296   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
297
298   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
299   /// accepts a single symbol (which should be a label or an external).
300   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
301
302   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
303
304   bool ParseDirectiveAbort(); // ".abort"
305   bool ParseDirectiveInclude(); // ".include"
306   bool ParseDirectiveIncbin(); // ".incbin"
307
308   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
309   // ".ifb" or ".ifnb", depending on ExpectBlank.
310   bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
311   // ".ifc" or ".ifnc", depending on ExpectEqual.
312   bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
313   // ".ifdef" or ".ifndef", depending on expect_defined
314   bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
315   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
316   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
317   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
318
319   /// ParseEscapedString - Parse the current token as a string which may include
320   /// escaped characters and return the string contents.
321   bool ParseEscapedString(std::string &Data);
322
323   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
324                                     MCSymbolRefExpr::VariantKind Variant);
325
326   // Macro-like directives
327   Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
328   void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
329                                 raw_svector_ostream &OS);
330   bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
331   bool ParseDirectiveIrp(SMLoc DirectiveLoc);  // ".irp"
332   bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
333   bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
334
335   // "_emit"
336   bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
337 };
338
339 /// \brief Generic implementations of directive handling, etc. which is shared
340 /// (or the default, at least) for all assembler parser.
341 class GenericAsmParser : public MCAsmParserExtension {
342   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
343   void AddDirectiveHandler(StringRef Directive) {
344     getParser().AddDirectiveHandler(this, Directive,
345                                     HandleDirective<GenericAsmParser, Handler>);
346   }
347 public:
348   GenericAsmParser() {}
349
350   AsmParser &getParser() {
351     return (AsmParser&) this->MCAsmParserExtension::getParser();
352   }
353
354   virtual void Initialize(MCAsmParser &Parser) {
355     // Call the base implementation.
356     this->MCAsmParserExtension::Initialize(Parser);
357
358     // Debugging directives.
359     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
360     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
361     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
362     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
363
364     // CFI directives.
365     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
366                                                                ".cfi_sections");
367     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
368                                                               ".cfi_startproc");
369     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
370                                                                 ".cfi_endproc");
371     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
372                                                          ".cfi_def_cfa");
373     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
374                                                          ".cfi_def_cfa_offset");
375     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
376                                                       ".cfi_adjust_cfa_offset");
377     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
378                                                        ".cfi_def_cfa_register");
379     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
380                                                                  ".cfi_offset");
381     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
382                                                              ".cfi_rel_offset");
383     AddDirectiveHandler<
384      &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
385     AddDirectiveHandler<
386             &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
387     AddDirectiveHandler<
388       &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
389     AddDirectiveHandler<
390       &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
391     AddDirectiveHandler<
392       &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
393     AddDirectiveHandler<
394       &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
395     AddDirectiveHandler<
396       &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
397     AddDirectiveHandler<
398       &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
399
400     // Macro directives.
401     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
402       ".macros_on");
403     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
404       ".macros_off");
405     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
406     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
407     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
408     AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
409
410     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
411     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
412   }
413
414   bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
415
416   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
417   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
418   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
419   bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
420   bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
421   bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
422   bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
423   bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
424   bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
425   bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
426   bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
427   bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
428   bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
429   bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
430   bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
431   bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
432   bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
433   bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
434   bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
435   bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
436
437   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
438   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
439   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
440   bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
441
442   bool ParseDirectiveLEB128(StringRef, SMLoc);
443 };
444
445 }
446
447 namespace llvm {
448
449 extern MCAsmParserExtension *createDarwinAsmParser();
450 extern MCAsmParserExtension *createELFAsmParser();
451 extern MCAsmParserExtension *createCOFFAsmParser();
452
453 }
454
455 enum { DEFAULT_ADDRSPACE = 0 };
456
457 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
458                      MCStreamer &_Out, const MCAsmInfo &_MAI)
459   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
460     GenericParser(new GenericAsmParser), PlatformParser(0),
461     CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
462     AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
463   // Save the old handler.
464   SavedDiagHandler = SrcMgr.getDiagHandler();
465   SavedDiagContext = SrcMgr.getDiagContext();
466   // Set our own handler which calls the saved handler.
467   SrcMgr.setDiagHandler(DiagHandler, this);
468   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
469
470   // Initialize the generic parser.
471   GenericParser->Initialize(*this);
472
473   // Initialize the platform / file format parser.
474   //
475   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
476   // created.
477   if (_MAI.hasMicrosoftFastStdCallMangling()) {
478     PlatformParser = createCOFFAsmParser();
479     PlatformParser->Initialize(*this);
480   } else if (_MAI.hasSubsectionsViaSymbols()) {
481     PlatformParser = createDarwinAsmParser();
482     PlatformParser->Initialize(*this);
483     IsDarwin = true;
484   } else {
485     PlatformParser = createELFAsmParser();
486     PlatformParser->Initialize(*this);
487   }
488 }
489
490 AsmParser::~AsmParser() {
491   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
492
493   // Destroy any macros.
494   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
495          ie = MacroMap.end(); it != ie; ++it)
496     delete it->getValue();
497
498   delete PlatformParser;
499   delete GenericParser;
500 }
501
502 void AsmParser::PrintMacroInstantiations() {
503   // Print the active macro instantiation stack.
504   for (std::vector<MacroInstantiation*>::const_reverse_iterator
505          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
506     PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
507                  "while in macro instantiation");
508 }
509
510 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
511   if (FatalAssemblerWarnings)
512     return Error(L, Msg, Ranges);
513   PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
514   PrintMacroInstantiations();
515   return false;
516 }
517
518 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
519   HadError = true;
520   PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
521   PrintMacroInstantiations();
522   return true;
523 }
524
525 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
526   std::string IncludedFile;
527   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
528   if (NewBuf == -1)
529     return true;
530
531   CurBuffer = NewBuf;
532
533   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
534
535   return false;
536 }
537
538 /// Process the specified .incbin file by seaching for it in the include paths
539 /// then just emitting the byte contents of the file to the streamer. This
540 /// returns true on failure.
541 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
542   std::string IncludedFile;
543   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
544   if (NewBuf == -1)
545     return true;
546
547   // Pick up the bytes from the file and emit them.
548   getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
549                           DEFAULT_ADDRSPACE);
550   return false;
551 }
552
553 void AsmParser::JumpToLoc(SMLoc Loc) {
554   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
555   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
556 }
557
558 const AsmToken &AsmParser::Lex() {
559   const AsmToken *tok = &Lexer.Lex();
560
561   if (tok->is(AsmToken::Eof)) {
562     // If this is the end of an included file, pop the parent file off the
563     // include stack.
564     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
565     if (ParentIncludeLoc != SMLoc()) {
566       JumpToLoc(ParentIncludeLoc);
567       tok = &Lexer.Lex();
568     }
569   }
570
571   if (tok->is(AsmToken::Error))
572     Error(Lexer.getErrLoc(), Lexer.getErr());
573
574   return *tok;
575 }
576
577 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
578   // Create the initial section, if requested.
579   if (!NoInitialTextSection)
580     Out.InitSections();
581
582   // Prime the lexer.
583   Lex();
584
585   HadError = false;
586   AsmCond StartingCondState = TheCondState;
587
588   // If we are generating dwarf for assembly source files save the initial text
589   // section and generate a .file directive.
590   if (getContext().getGenDwarfForAssembly()) {
591     getContext().setGenDwarfSection(getStreamer().getCurrentSection());
592     MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
593     getStreamer().EmitLabel(SectionStartSym);
594     getContext().setGenDwarfSectionStartSym(SectionStartSym);
595     getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
596       StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
597   }
598
599   // While we have input, parse each statement.
600   while (Lexer.isNot(AsmToken::Eof)) {
601     ParseStatementInfo Info;
602     if (!ParseStatement(Info)) continue;
603
604     // We had an error, validate that one was emitted and recover by skipping to
605     // the next line.
606     assert(HadError && "Parse statement returned an error, but none emitted!");
607     EatToEndOfStatement();
608   }
609
610   if (TheCondState.TheCond != StartingCondState.TheCond ||
611       TheCondState.Ignore != StartingCondState.Ignore)
612     return TokError("unmatched .ifs or .elses");
613
614   // Check to see there are no empty DwarfFile slots.
615   const std::vector<MCDwarfFile *> &MCDwarfFiles =
616     getContext().getMCDwarfFiles();
617   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
618     if (!MCDwarfFiles[i])
619       TokError("unassigned file number: " + Twine(i) + " for .file directives");
620   }
621
622   // Check to see that all assembler local symbols were actually defined.
623   // Targets that don't do subsections via symbols may not want this, though,
624   // so conservatively exclude them. Only do this if we're finalizing, though,
625   // as otherwise we won't necessarilly have seen everything yet.
626   if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
627     const MCContext::SymbolTable &Symbols = getContext().getSymbols();
628     for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
629          e = Symbols.end();
630          i != e; ++i) {
631       MCSymbol *Sym = i->getValue();
632       // Variable symbols may not be marked as defined, so check those
633       // explicitly. If we know it's a variable, we have a definition for
634       // the purposes of this check.
635       if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
636         // FIXME: We would really like to refer back to where the symbol was
637         // first referenced for a source location. We need to add something
638         // to track that. Currently, we just point to the end of the file.
639         PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
640                      "assembler local symbol '" + Sym->getName() +
641                      "' not defined");
642     }
643   }
644
645
646   // Finalize the output stream if there are no errors and if the client wants
647   // us to.
648   if (!HadError && !NoFinalize)
649     Out.Finish();
650
651   return HadError;
652 }
653
654 void AsmParser::CheckForValidSection() {
655   if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
656     TokError("expected section directive before assembly directive");
657     Out.SwitchSection(Ctx.getMachOSection(
658                         "__TEXT", "__text",
659                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
660                         0, SectionKind::getText()));
661   }
662 }
663
664 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
665 void AsmParser::EatToEndOfStatement() {
666   while (Lexer.isNot(AsmToken::EndOfStatement) &&
667          Lexer.isNot(AsmToken::Eof))
668     Lex();
669
670   // Eat EOL.
671   if (Lexer.is(AsmToken::EndOfStatement))
672     Lex();
673 }
674
675 StringRef AsmParser::ParseStringToEndOfStatement() {
676   const char *Start = getTok().getLoc().getPointer();
677
678   while (Lexer.isNot(AsmToken::EndOfStatement) &&
679          Lexer.isNot(AsmToken::Eof))
680     Lex();
681
682   const char *End = getTok().getLoc().getPointer();
683   return StringRef(Start, End - Start);
684 }
685
686 StringRef AsmParser::ParseStringToComma() {
687   const char *Start = getTok().getLoc().getPointer();
688
689   while (Lexer.isNot(AsmToken::EndOfStatement) &&
690          Lexer.isNot(AsmToken::Comma) &&
691          Lexer.isNot(AsmToken::Eof))
692     Lex();
693
694   const char *End = getTok().getLoc().getPointer();
695   return StringRef(Start, End - Start);
696 }
697
698 /// ParseParenExpr - Parse a paren expression and return it.
699 /// NOTE: This assumes the leading '(' has already been consumed.
700 ///
701 /// parenexpr ::= expr)
702 ///
703 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
704   if (ParseExpression(Res)) return true;
705   if (Lexer.isNot(AsmToken::RParen))
706     return TokError("expected ')' in parentheses expression");
707   EndLoc = Lexer.getLoc();
708   Lex();
709   return false;
710 }
711
712 /// ParseBracketExpr - Parse a bracket expression and return it.
713 /// NOTE: This assumes the leading '[' has already been consumed.
714 ///
715 /// bracketexpr ::= expr]
716 ///
717 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
718   if (ParseExpression(Res)) return true;
719   if (Lexer.isNot(AsmToken::RBrac))
720     return TokError("expected ']' in brackets expression");
721   EndLoc = Lexer.getLoc();
722   Lex();
723   return false;
724 }
725
726 /// ParsePrimaryExpr - Parse a primary expression and return it.
727 ///  primaryexpr ::= (parenexpr
728 ///  primaryexpr ::= symbol
729 ///  primaryexpr ::= number
730 ///  primaryexpr ::= '.'
731 ///  primaryexpr ::= ~,+,- primaryexpr
732 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
733   switch (Lexer.getKind()) {
734   default:
735     return TokError("unknown token in expression");
736   // If we have an error assume that we've already handled it.
737   case AsmToken::Error:
738     return true;
739   case AsmToken::Exclaim:
740     Lex(); // Eat the operator.
741     if (ParsePrimaryExpr(Res, EndLoc))
742       return true;
743     Res = MCUnaryExpr::CreateLNot(Res, getContext());
744     return false;
745   case AsmToken::Dollar:
746   case AsmToken::String:
747   case AsmToken::Identifier: {
748     EndLoc = Lexer.getLoc();
749
750     StringRef Identifier;
751     if (ParseIdentifier(Identifier))
752       return true;
753
754     // This is a symbol reference.
755     std::pair<StringRef, StringRef> Split = Identifier.split('@');
756     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
757
758     // Lookup the symbol variant if used.
759     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
760     if (Split.first.size() != Identifier.size()) {
761       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
762       if (Variant == MCSymbolRefExpr::VK_Invalid) {
763         Variant = MCSymbolRefExpr::VK_None;
764         return TokError("invalid variant '" + Split.second + "'");
765       }
766     }
767
768     // If this is an absolute variable reference, substitute it now to preserve
769     // semantics in the face of reassignment.
770     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
771       if (Variant)
772         return Error(EndLoc, "unexpected modifier on variable reference");
773
774       Res = Sym->getVariableValue();
775       return false;
776     }
777
778     // Otherwise create a symbol ref.
779     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
780     return false;
781   }
782   case AsmToken::Integer: {
783     SMLoc Loc = getTok().getLoc();
784     int64_t IntVal = getTok().getIntVal();
785     Res = MCConstantExpr::Create(IntVal, getContext());
786     EndLoc = Lexer.getLoc();
787     Lex(); // Eat token.
788     // Look for 'b' or 'f' following an Integer as a directional label
789     if (Lexer.getKind() == AsmToken::Identifier) {
790       StringRef IDVal = getTok().getString();
791       if (IDVal == "f" || IDVal == "b"){
792         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
793                                                       IDVal == "f" ? 1 : 0);
794         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
795                                       getContext());
796         if (IDVal == "b" && Sym->isUndefined())
797           return Error(Loc, "invalid reference to undefined symbol");
798         EndLoc = Lexer.getLoc();
799         Lex(); // Eat identifier.
800       }
801     }
802     return false;
803   }
804   case AsmToken::Real: {
805     APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
806     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
807     Res = MCConstantExpr::Create(IntVal, getContext());
808     Lex(); // Eat token.
809     return false;
810   }
811   case AsmToken::Dot: {
812     // This is a '.' reference, which references the current PC.  Emit a
813     // temporary label to the streamer and refer to it.
814     MCSymbol *Sym = Ctx.CreateTempSymbol();
815     Out.EmitLabel(Sym);
816     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
817     EndLoc = Lexer.getLoc();
818     Lex(); // Eat identifier.
819     return false;
820   }
821   case AsmToken::LParen:
822     Lex(); // Eat the '('.
823     return ParseParenExpr(Res, EndLoc);
824   case AsmToken::LBrac:
825     if (!PlatformParser->HasBracketExpressions())
826       return TokError("brackets expression not supported on this target");
827     Lex(); // Eat the '['.
828     return ParseBracketExpr(Res, EndLoc);
829   case AsmToken::Minus:
830     Lex(); // Eat the operator.
831     if (ParsePrimaryExpr(Res, EndLoc))
832       return true;
833     Res = MCUnaryExpr::CreateMinus(Res, getContext());
834     return false;
835   case AsmToken::Plus:
836     Lex(); // Eat the operator.
837     if (ParsePrimaryExpr(Res, EndLoc))
838       return true;
839     Res = MCUnaryExpr::CreatePlus(Res, getContext());
840     return false;
841   case AsmToken::Tilde:
842     Lex(); // Eat the operator.
843     if (ParsePrimaryExpr(Res, EndLoc))
844       return true;
845     Res = MCUnaryExpr::CreateNot(Res, getContext());
846     return false;
847   }
848 }
849
850 bool AsmParser::ParseExpression(const MCExpr *&Res) {
851   SMLoc EndLoc;
852   return ParseExpression(Res, EndLoc);
853 }
854
855 const MCExpr *
856 AsmParser::ApplyModifierToExpr(const MCExpr *E,
857                                MCSymbolRefExpr::VariantKind Variant) {
858   // Recurse over the given expression, rebuilding it to apply the given variant
859   // if there is exactly one symbol.
860   switch (E->getKind()) {
861   case MCExpr::Target:
862   case MCExpr::Constant:
863     return 0;
864
865   case MCExpr::SymbolRef: {
866     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
867
868     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
869       TokError("invalid variant on expression '" +
870                getTok().getIdentifier() + "' (already modified)");
871       return E;
872     }
873
874     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
875   }
876
877   case MCExpr::Unary: {
878     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
879     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
880     if (!Sub)
881       return 0;
882     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
883   }
884
885   case MCExpr::Binary: {
886     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
887     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
888     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
889
890     if (!LHS && !RHS)
891       return 0;
892
893     if (!LHS) LHS = BE->getLHS();
894     if (!RHS) RHS = BE->getRHS();
895
896     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
897   }
898   }
899
900   llvm_unreachable("Invalid expression kind!");
901 }
902
903 /// ParseExpression - Parse an expression and return it.
904 ///
905 ///  expr ::= expr &&,|| expr               -> lowest.
906 ///  expr ::= expr |,^,&,! expr
907 ///  expr ::= expr ==,!=,<>,<,<=,>,>= expr
908 ///  expr ::= expr <<,>> expr
909 ///  expr ::= expr +,- expr
910 ///  expr ::= expr *,/,% expr               -> highest.
911 ///  expr ::= primaryexpr
912 ///
913 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
914   // Parse the expression.
915   Res = 0;
916   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
917     return true;
918
919   // As a special case, we support 'a op b @ modifier' by rewriting the
920   // expression to include the modifier. This is inefficient, but in general we
921   // expect users to use 'a@modifier op b'.
922   if (Lexer.getKind() == AsmToken::At) {
923     Lex();
924
925     if (Lexer.isNot(AsmToken::Identifier))
926       return TokError("unexpected symbol modifier following '@'");
927
928     MCSymbolRefExpr::VariantKind Variant =
929       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
930     if (Variant == MCSymbolRefExpr::VK_Invalid)
931       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
932
933     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
934     if (!ModifiedRes) {
935       return TokError("invalid modifier '" + getTok().getIdentifier() +
936                       "' (no symbols present)");
937     }
938
939     Res = ModifiedRes;
940     Lex();
941   }
942
943   // Try to constant fold it up front, if possible.
944   int64_t Value;
945   if (Res->EvaluateAsAbsolute(Value))
946     Res = MCConstantExpr::Create(Value, getContext());
947
948   return false;
949 }
950
951 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
952   Res = 0;
953   return ParseParenExpr(Res, EndLoc) ||
954          ParseBinOpRHS(1, Res, EndLoc);
955 }
956
957 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
958   const MCExpr *Expr;
959
960   SMLoc StartLoc = Lexer.getLoc();
961   if (ParseExpression(Expr))
962     return true;
963
964   if (!Expr->EvaluateAsAbsolute(Res))
965     return Error(StartLoc, "expected absolute expression");
966
967   return false;
968 }
969
970 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
971                                    MCBinaryExpr::Opcode &Kind) {
972   switch (K) {
973   default:
974     return 0;    // not a binop.
975
976     // Lowest Precedence: &&, ||
977   case AsmToken::AmpAmp:
978     Kind = MCBinaryExpr::LAnd;
979     return 1;
980   case AsmToken::PipePipe:
981     Kind = MCBinaryExpr::LOr;
982     return 1;
983
984
985     // Low Precedence: |, &, ^
986     //
987     // FIXME: gas seems to support '!' as an infix operator?
988   case AsmToken::Pipe:
989     Kind = MCBinaryExpr::Or;
990     return 2;
991   case AsmToken::Caret:
992     Kind = MCBinaryExpr::Xor;
993     return 2;
994   case AsmToken::Amp:
995     Kind = MCBinaryExpr::And;
996     return 2;
997
998     // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
999   case AsmToken::EqualEqual:
1000     Kind = MCBinaryExpr::EQ;
1001     return 3;
1002   case AsmToken::ExclaimEqual:
1003   case AsmToken::LessGreater:
1004     Kind = MCBinaryExpr::NE;
1005     return 3;
1006   case AsmToken::Less:
1007     Kind = MCBinaryExpr::LT;
1008     return 3;
1009   case AsmToken::LessEqual:
1010     Kind = MCBinaryExpr::LTE;
1011     return 3;
1012   case AsmToken::Greater:
1013     Kind = MCBinaryExpr::GT;
1014     return 3;
1015   case AsmToken::GreaterEqual:
1016     Kind = MCBinaryExpr::GTE;
1017     return 3;
1018
1019     // Intermediate Precedence: <<, >>
1020   case AsmToken::LessLess:
1021     Kind = MCBinaryExpr::Shl;
1022     return 4;
1023   case AsmToken::GreaterGreater:
1024     Kind = MCBinaryExpr::Shr;
1025     return 4;
1026
1027     // High Intermediate Precedence: +, -
1028   case AsmToken::Plus:
1029     Kind = MCBinaryExpr::Add;
1030     return 5;
1031   case AsmToken::Minus:
1032     Kind = MCBinaryExpr::Sub;
1033     return 5;
1034
1035     // Highest Precedence: *, /, %
1036   case AsmToken::Star:
1037     Kind = MCBinaryExpr::Mul;
1038     return 6;
1039   case AsmToken::Slash:
1040     Kind = MCBinaryExpr::Div;
1041     return 6;
1042   case AsmToken::Percent:
1043     Kind = MCBinaryExpr::Mod;
1044     return 6;
1045   }
1046 }
1047
1048
1049 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1050 /// Res contains the LHS of the expression on input.
1051 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1052                               SMLoc &EndLoc) {
1053   while (1) {
1054     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1055     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1056
1057     // If the next token is lower precedence than we are allowed to eat, return
1058     // successfully with what we ate already.
1059     if (TokPrec < Precedence)
1060       return false;
1061
1062     Lex();
1063
1064     // Eat the next primary expression.
1065     const MCExpr *RHS;
1066     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1067
1068     // If BinOp binds less tightly with RHS than the operator after RHS, let
1069     // the pending operator take RHS as its LHS.
1070     MCBinaryExpr::Opcode Dummy;
1071     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1072     if (TokPrec < NextTokPrec) {
1073       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1074     }
1075
1076     // Merge LHS and RHS according to operator.
1077     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1078   }
1079 }
1080
1081 /// ParseStatement:
1082 ///   ::= EndOfStatement
1083 ///   ::= Label* Directive ...Operands... EndOfStatement
1084 ///   ::= Label* Identifier OperandList* EndOfStatement
1085 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1086   if (Lexer.is(AsmToken::EndOfStatement)) {
1087     Out.AddBlankLine();
1088     Lex();
1089     return false;
1090   }
1091
1092   // Statements always start with an identifier or are a full line comment.
1093   AsmToken ID = getTok();
1094   SMLoc IDLoc = ID.getLoc();
1095   StringRef IDVal;
1096   int64_t LocalLabelVal = -1;
1097   // A full line comment is a '#' as the first token.
1098   if (Lexer.is(AsmToken::Hash))
1099     return ParseCppHashLineFilenameComment(IDLoc);
1100
1101   // Allow an integer followed by a ':' as a directional local label.
1102   if (Lexer.is(AsmToken::Integer)) {
1103     LocalLabelVal = getTok().getIntVal();
1104     if (LocalLabelVal < 0) {
1105       if (!TheCondState.Ignore)
1106         return TokError("unexpected token at start of statement");
1107       IDVal = "";
1108     }
1109     else {
1110       IDVal = getTok().getString();
1111       Lex(); // Consume the integer token to be used as an identifier token.
1112       if (Lexer.getKind() != AsmToken::Colon) {
1113         if (!TheCondState.Ignore)
1114           return TokError("unexpected token at start of statement");
1115       }
1116     }
1117
1118   } else if (Lexer.is(AsmToken::Dot)) {
1119     // Treat '.' as a valid identifier in this context.
1120     Lex();
1121     IDVal = ".";
1122
1123   } else if (ParseIdentifier(IDVal)) {
1124     if (!TheCondState.Ignore)
1125       return TokError("unexpected token at start of statement");
1126     IDVal = "";
1127   }
1128
1129
1130   // Handle conditional assembly here before checking for skipping.  We
1131   // have to do this so that .endif isn't skipped in a ".if 0" block for
1132   // example.
1133   if (IDVal == ".if")
1134     return ParseDirectiveIf(IDLoc);
1135   if (IDVal == ".ifb")
1136     return ParseDirectiveIfb(IDLoc, true);
1137   if (IDVal == ".ifnb")
1138     return ParseDirectiveIfb(IDLoc, false);
1139   if (IDVal == ".ifc")
1140     return ParseDirectiveIfc(IDLoc, true);
1141   if (IDVal == ".ifnc")
1142     return ParseDirectiveIfc(IDLoc, false);
1143   if (IDVal == ".ifdef")
1144     return ParseDirectiveIfdef(IDLoc, true);
1145   if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1146     return ParseDirectiveIfdef(IDLoc, false);
1147   if (IDVal == ".elseif")
1148     return ParseDirectiveElseIf(IDLoc);
1149   if (IDVal == ".else")
1150     return ParseDirectiveElse(IDLoc);
1151   if (IDVal == ".endif")
1152     return ParseDirectiveEndIf(IDLoc);
1153
1154   // If we are in a ".if 0" block, ignore this statement.
1155   if (TheCondState.Ignore) {
1156     EatToEndOfStatement();
1157     return false;
1158   }
1159
1160   // FIXME: Recurse on local labels?
1161
1162   // See what kind of statement we have.
1163   switch (Lexer.getKind()) {
1164   case AsmToken::Colon: {
1165     CheckForValidSection();
1166
1167     // identifier ':'   -> Label.
1168     Lex();
1169
1170     // Diagnose attempt to use '.' as a label.
1171     if (IDVal == ".")
1172       return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1173
1174     // Diagnose attempt to use a variable as a label.
1175     //
1176     // FIXME: Diagnostics. Note the location of the definition as a label.
1177     // FIXME: This doesn't diagnose assignment to a symbol which has been
1178     // implicitly marked as external.
1179     MCSymbol *Sym;
1180     if (LocalLabelVal == -1)
1181       Sym = getContext().GetOrCreateSymbol(IDVal);
1182     else
1183       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1184     if (!Sym->isUndefined() || Sym->isVariable())
1185       return Error(IDLoc, "invalid symbol redefinition");
1186
1187     // Emit the label.
1188     Out.EmitLabel(Sym);
1189
1190     // If we are generating dwarf for assembly source files then gather the
1191     // info to make a dwarf label entry for this label if needed.
1192     if (getContext().getGenDwarfForAssembly())
1193       MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1194                                  IDLoc);
1195
1196     // Consume any end of statement token, if present, to avoid spurious
1197     // AddBlankLine calls().
1198     if (Lexer.is(AsmToken::EndOfStatement)) {
1199       Lex();
1200       if (Lexer.is(AsmToken::Eof))
1201         return false;
1202     }
1203
1204     return false;
1205   }
1206
1207   case AsmToken::Equal:
1208     // identifier '=' ... -> assignment statement
1209     Lex();
1210
1211     return ParseAssignment(IDVal, true);
1212
1213   default: // Normal instruction or directive.
1214     break;
1215   }
1216
1217   // If macros are enabled, check to see if this is a macro instantiation.
1218   if (MacrosEnabled)
1219     if (const Macro *M = MacroMap.lookup(IDVal))
1220       return HandleMacroEntry(IDVal, IDLoc, M);
1221
1222   // Otherwise, we have a normal instruction or directive.
1223   if (IDVal[0] == '.' && IDVal != ".") {
1224
1225     // Target hook for parsing target specific directives.
1226     if (!getTargetParser().ParseDirective(ID))
1227       return false;
1228
1229     // Assembler features
1230     if (IDVal == ".set" || IDVal == ".equ")
1231       return ParseDirectiveSet(IDVal, true);
1232     if (IDVal == ".equiv")
1233       return ParseDirectiveSet(IDVal, false);
1234
1235     // Data directives
1236
1237     if (IDVal == ".ascii")
1238       return ParseDirectiveAscii(IDVal, false);
1239     if (IDVal == ".asciz" || IDVal == ".string")
1240       return ParseDirectiveAscii(IDVal, true);
1241
1242     if (IDVal == ".byte")
1243       return ParseDirectiveValue(1);
1244     if (IDVal == ".short")
1245       return ParseDirectiveValue(2);
1246     if (IDVal == ".value")
1247       return ParseDirectiveValue(2);
1248     if (IDVal == ".2byte")
1249       return ParseDirectiveValue(2);
1250     if (IDVal == ".long")
1251       return ParseDirectiveValue(4);
1252     if (IDVal == ".int")
1253       return ParseDirectiveValue(4);
1254     if (IDVal == ".4byte")
1255       return ParseDirectiveValue(4);
1256     if (IDVal == ".quad")
1257       return ParseDirectiveValue(8);
1258     if (IDVal == ".8byte")
1259       return ParseDirectiveValue(8);
1260     if (IDVal == ".single" || IDVal == ".float")
1261       return ParseDirectiveRealValue(APFloat::IEEEsingle);
1262     if (IDVal == ".double")
1263       return ParseDirectiveRealValue(APFloat::IEEEdouble);
1264
1265     if (IDVal == ".align") {
1266       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1267       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1268     }
1269     if (IDVal == ".align32") {
1270       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1271       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1272     }
1273     if (IDVal == ".balign")
1274       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1275     if (IDVal == ".balignw")
1276       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1277     if (IDVal == ".balignl")
1278       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1279     if (IDVal == ".p2align")
1280       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1281     if (IDVal == ".p2alignw")
1282       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1283     if (IDVal == ".p2alignl")
1284       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1285
1286     if (IDVal == ".org")
1287       return ParseDirectiveOrg();
1288
1289     if (IDVal == ".fill")
1290       return ParseDirectiveFill();
1291     if (IDVal == ".space" || IDVal == ".skip")
1292       return ParseDirectiveSpace();
1293     if (IDVal == ".zero")
1294       return ParseDirectiveZero();
1295
1296     // Symbol attribute directives
1297
1298     if (IDVal == ".extern") {
1299       EatToEndOfStatement(); // .extern is the default, ignore it.
1300       return false;
1301     }
1302     if (IDVal == ".globl" || IDVal == ".global")
1303       return ParseDirectiveSymbolAttribute(MCSA_Global);
1304     if (IDVal == ".indirect_symbol")
1305       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1306     if (IDVal == ".lazy_reference")
1307       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1308     if (IDVal == ".no_dead_strip")
1309       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1310     if (IDVal == ".symbol_resolver")
1311       return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1312     if (IDVal == ".private_extern")
1313       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1314     if (IDVal == ".reference")
1315       return ParseDirectiveSymbolAttribute(MCSA_Reference);
1316     if (IDVal == ".weak_definition")
1317       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1318     if (IDVal == ".weak_reference")
1319       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1320     if (IDVal == ".weak_def_can_be_hidden")
1321       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1322
1323     if (IDVal == ".comm" || IDVal == ".common")
1324       return ParseDirectiveComm(/*IsLocal=*/false);
1325     if (IDVal == ".lcomm")
1326       return ParseDirectiveComm(/*IsLocal=*/true);
1327
1328     if (IDVal == ".abort")
1329       return ParseDirectiveAbort();
1330     if (IDVal == ".include")
1331       return ParseDirectiveInclude();
1332     if (IDVal == ".incbin")
1333       return ParseDirectiveIncbin();
1334
1335     if (IDVal == ".code16" || IDVal == ".code16gcc")
1336       return TokError(Twine(IDVal) + " not supported yet");
1337
1338     // Macro-like directives
1339     if (IDVal == ".rept")
1340       return ParseDirectiveRept(IDLoc);
1341     if (IDVal == ".irp")
1342       return ParseDirectiveIrp(IDLoc);
1343     if (IDVal == ".irpc")
1344       return ParseDirectiveIrpc(IDLoc);
1345     if (IDVal == ".endr")
1346       return ParseDirectiveEndr(IDLoc);
1347
1348     // Look up the handler in the handler table.
1349     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1350       DirectiveMap.lookup(IDVal);
1351     if (Handler.first)
1352       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1353
1354
1355     return Error(IDLoc, "unknown directive");
1356   }
1357
1358   // _emit
1359   if (ParsingInlineAsm && IDVal == "_emit")
1360     return ParseDirectiveEmit(IDLoc, Info);
1361
1362   CheckForValidSection();
1363
1364   // Canonicalize the opcode to lower case.
1365   SmallString<128> OpcodeStr;
1366   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1367     OpcodeStr.push_back(tolower(IDVal[i]));
1368
1369   ParseInstructionInfo IInfo(Info.AsmRewrites);
1370   bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1371                                                      IDLoc,Info.ParsedOperands);
1372
1373   // Dump the parsed representation, if requested.
1374   if (getShowParsedOperands()) {
1375     SmallString<256> Str;
1376     raw_svector_ostream OS(Str);
1377     OS << "parsed instruction: [";
1378     for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1379       if (i != 0)
1380         OS << ", ";
1381       Info.ParsedOperands[i]->print(OS);
1382     }
1383     OS << "]";
1384
1385     PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1386   }
1387
1388   // If we are generating dwarf for assembly source files and the current
1389   // section is the initial text section then generate a .loc directive for
1390   // the instruction.
1391   if (!HadError && getContext().getGenDwarfForAssembly() &&
1392       getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1393
1394      unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1395
1396      // If we previously parsed a cpp hash file line comment then make sure the
1397      // current Dwarf File is for the CppHashFilename if not then emit the
1398      // Dwarf File table for it and adjust the line number for the .loc.
1399      const std::vector<MCDwarfFile *> &MCDwarfFiles =
1400        getContext().getMCDwarfFiles();
1401      if (CppHashFilename.size() != 0) {
1402        if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1403           CppHashFilename)
1404          getStreamer().EmitDwarfFileDirective(
1405            getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1406
1407        unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1408        Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1409      }
1410
1411     getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1412                                         Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1413                                         DWARF2_FLAG_IS_STMT : 0, 0, 0,
1414                                         StringRef());
1415   }
1416
1417   // If parsing succeeded, match the instruction.
1418   if (!HadError) {
1419     unsigned ErrorInfo;
1420     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1421                                                          Info.ParsedOperands,
1422                                                          Out, ErrorInfo,
1423                                                          ParsingInlineAsm);
1424   }
1425
1426   // Don't skip the rest of the line, the instruction parser is responsible for
1427   // that.
1428   return false;
1429 }
1430
1431 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1432 /// since they may not be able to be tokenized to get to the end of line token.
1433 void AsmParser::EatToEndOfLine() {
1434   if (!Lexer.is(AsmToken::EndOfStatement))
1435     Lexer.LexUntilEndOfLine();
1436  // Eat EOL.
1437  Lex();
1438 }
1439
1440 /// ParseCppHashLineFilenameComment as this:
1441 ///   ::= # number "filename"
1442 /// or just as a full line comment if it doesn't have a number and a string.
1443 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1444   Lex(); // Eat the hash token.
1445
1446   if (getLexer().isNot(AsmToken::Integer)) {
1447     // Consume the line since in cases it is not a well-formed line directive,
1448     // as if were simply a full line comment.
1449     EatToEndOfLine();
1450     return false;
1451   }
1452
1453   int64_t LineNumber = getTok().getIntVal();
1454   Lex();
1455
1456   if (getLexer().isNot(AsmToken::String)) {
1457     EatToEndOfLine();
1458     return false;
1459   }
1460
1461   StringRef Filename = getTok().getString();
1462   // Get rid of the enclosing quotes.
1463   Filename = Filename.substr(1, Filename.size()-2);
1464
1465   // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1466   CppHashLoc = L;
1467   CppHashFilename = Filename;
1468   CppHashLineNumber = LineNumber;
1469   CppHashBuf = CurBuffer;
1470
1471   // Ignore any trailing characters, they're just comment.
1472   EatToEndOfLine();
1473   return false;
1474 }
1475
1476 /// DiagHandler - will use the last parsed cpp hash line filename comment
1477 /// for the Filename and LineNo if any in the diagnostic.
1478 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1479   const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1480   raw_ostream &OS = errs();
1481
1482   const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1483   const SMLoc &DiagLoc = Diag.getLoc();
1484   int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1485   int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1486
1487   // Like SourceMgr::PrintMessage() we need to print the include stack if any
1488   // before printing the message.
1489   int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1490   if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1491      SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1492      DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1493   }
1494
1495   // If we have not parsed a cpp hash line filename comment or the source 
1496   // manager changed or buffer changed (like in a nested include) then just
1497   // print the normal diagnostic using its Filename and LineNo.
1498   if (!Parser->CppHashLineNumber ||
1499       &DiagSrcMgr != &Parser->SrcMgr ||
1500       DiagBuf != CppHashBuf) {
1501     if (Parser->SavedDiagHandler)
1502       Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1503     else
1504       Diag.print(0, OS);
1505     return;
1506   }
1507
1508   // Use the CppHashFilename and calculate a line number based on the 
1509   // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1510   // the diagnostic.
1511   const std::string Filename = Parser->CppHashFilename;
1512
1513   int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1514   int CppHashLocLineNo =
1515       Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1516   int LineNo = Parser->CppHashLineNumber - 1 +
1517                (DiagLocLineNo - CppHashLocLineNo);
1518
1519   SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1520                        Filename, LineNo, Diag.getColumnNo(),
1521                        Diag.getKind(), Diag.getMessage(),
1522                        Diag.getLineContents(), Diag.getRanges());
1523
1524   if (Parser->SavedDiagHandler)
1525     Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1526   else
1527     NewDiag.print(0, OS);
1528 }
1529
1530 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1531 // difference being that that function accepts '@' as part of identifiers and
1532 // we can't do that. AsmLexer.cpp should probably be changed to handle
1533 // '@' as a special case when needed.
1534 static bool isIdentifierChar(char c) {
1535   return isalnum(c) || c == '_' || c == '$' || c == '.';
1536 }
1537
1538 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1539                             const MacroParameters &Parameters,
1540                             const MacroArguments &A,
1541                             const SMLoc &L) {
1542   unsigned NParameters = Parameters.size();
1543   if (NParameters != 0 && NParameters != A.size())
1544     return Error(L, "Wrong number of arguments");
1545
1546   // A macro without parameters is handled differently on Darwin:
1547   // gas accepts no arguments and does no substitutions
1548   while (!Body.empty()) {
1549     // Scan for the next substitution.
1550     std::size_t End = Body.size(), Pos = 0;
1551     for (; Pos != End; ++Pos) {
1552       // Check for a substitution or escape.
1553       if (!NParameters) {
1554         // This macro has no parameters, look for $0, $1, etc.
1555         if (Body[Pos] != '$' || Pos + 1 == End)
1556           continue;
1557
1558         char Next = Body[Pos + 1];
1559         if (Next == '$' || Next == 'n' || isdigit(Next))
1560           break;
1561       } else {
1562         // This macro has parameters, look for \foo, \bar, etc.
1563         if (Body[Pos] == '\\' && Pos + 1 != End)
1564           break;
1565       }
1566     }
1567
1568     // Add the prefix.
1569     OS << Body.slice(0, Pos);
1570
1571     // Check if we reached the end.
1572     if (Pos == End)
1573       break;
1574
1575     if (!NParameters) {
1576       switch (Body[Pos+1]) {
1577         // $$ => $
1578       case '$':
1579         OS << '$';
1580         break;
1581
1582         // $n => number of arguments
1583       case 'n':
1584         OS << A.size();
1585         break;
1586
1587         // $[0-9] => argument
1588       default: {
1589         // Missing arguments are ignored.
1590         unsigned Index = Body[Pos+1] - '0';
1591         if (Index >= A.size())
1592           break;
1593
1594         // Otherwise substitute with the token values, with spaces eliminated.
1595         for (MacroArgument::const_iterator it = A[Index].begin(),
1596                ie = A[Index].end(); it != ie; ++it)
1597           OS << it->getString();
1598         break;
1599       }
1600       }
1601       Pos += 2;
1602     } else {
1603       unsigned I = Pos + 1;
1604       while (isIdentifierChar(Body[I]) && I + 1 != End)
1605         ++I;
1606
1607       const char *Begin = Body.data() + Pos +1;
1608       StringRef Argument(Begin, I - (Pos +1));
1609       unsigned Index = 0;
1610       for (; Index < NParameters; ++Index)
1611         if (Parameters[Index].first == Argument)
1612           break;
1613
1614       if (Index == NParameters) {
1615           if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1616             Pos += 3;
1617           else {
1618             OS << '\\' << Argument;
1619             Pos = I;
1620           }
1621       } else {
1622         for (MacroArgument::const_iterator it = A[Index].begin(),
1623                ie = A[Index].end(); it != ie; ++it)
1624           if (it->getKind() == AsmToken::String)
1625             OS << it->getStringContents();
1626           else
1627             OS << it->getString();
1628
1629         Pos += 1 + Argument.size();
1630       }
1631     }
1632     // Update the scan point.
1633     Body = Body.substr(Pos);
1634   }
1635
1636   return false;
1637 }
1638
1639 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1640                                        MemoryBuffer *I)
1641   : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1642 {
1643 }
1644
1645 static bool IsOperator(AsmToken::TokenKind kind)
1646 {
1647   switch (kind)
1648   {
1649     default:
1650       return false;
1651     case AsmToken::Plus:
1652     case AsmToken::Minus:
1653     case AsmToken::Tilde:
1654     case AsmToken::Slash:
1655     case AsmToken::Star:
1656     case AsmToken::Dot:
1657     case AsmToken::Equal:
1658     case AsmToken::EqualEqual:
1659     case AsmToken::Pipe:
1660     case AsmToken::PipePipe:
1661     case AsmToken::Caret:
1662     case AsmToken::Amp:
1663     case AsmToken::AmpAmp:
1664     case AsmToken::Exclaim:
1665     case AsmToken::ExclaimEqual:
1666     case AsmToken::Percent:
1667     case AsmToken::Less:
1668     case AsmToken::LessEqual:
1669     case AsmToken::LessLess:
1670     case AsmToken::LessGreater:
1671     case AsmToken::Greater:
1672     case AsmToken::GreaterEqual:
1673     case AsmToken::GreaterGreater:
1674       return true;
1675   }
1676 }
1677
1678 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1679 /// This is used for both default macro parameter values and the
1680 /// arguments in macro invocations
1681 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1682                                    AsmToken::TokenKind &ArgumentDelimiter) {
1683   unsigned ParenLevel = 0;
1684   unsigned AddTokens = 0;
1685
1686   // gas accepts arguments separated by whitespace, except on Darwin
1687   if (!IsDarwin)
1688     Lexer.setSkipSpace(false);
1689
1690   for (;;) {
1691     if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1692       Lexer.setSkipSpace(true);
1693       return TokError("unexpected token in macro instantiation");
1694     }
1695
1696     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1697       // Spaces and commas cannot be mixed to delimit parameters
1698       if (ArgumentDelimiter == AsmToken::Eof)
1699         ArgumentDelimiter = AsmToken::Comma;
1700       else if (ArgumentDelimiter != AsmToken::Comma) {
1701         Lexer.setSkipSpace(true);
1702         return TokError("expected ' ' for macro argument separator");
1703       }
1704       break;
1705     }
1706
1707     if (Lexer.is(AsmToken::Space)) {
1708       Lex(); // Eat spaces
1709
1710       // Spaces can delimit parameters, but could also be part an expression.
1711       // If the token after a space is an operator, add the token and the next
1712       // one into this argument
1713       if (ArgumentDelimiter == AsmToken::Space ||
1714           ArgumentDelimiter == AsmToken::Eof) {
1715         if (IsOperator(Lexer.getKind())) {
1716           // Check to see whether the token is used as an operator,
1717           // or part of an identifier
1718           const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1719           if (*NextChar == ' ')
1720             AddTokens = 2;
1721         }
1722
1723         if (!AddTokens && ParenLevel == 0) {
1724           if (ArgumentDelimiter == AsmToken::Eof &&
1725               !IsOperator(Lexer.getKind()))
1726             ArgumentDelimiter = AsmToken::Space;
1727           break;
1728         }
1729       }
1730     }
1731
1732     // HandleMacroEntry relies on not advancing the lexer here
1733     // to be able to fill in the remaining default parameter values
1734     if (Lexer.is(AsmToken::EndOfStatement))
1735       break;
1736
1737     // Adjust the current parentheses level.
1738     if (Lexer.is(AsmToken::LParen))
1739       ++ParenLevel;
1740     else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1741       --ParenLevel;
1742
1743     // Append the token to the current argument list.
1744     MA.push_back(getTok());
1745     if (AddTokens)
1746       AddTokens--;
1747     Lex();
1748   }
1749
1750   Lexer.setSkipSpace(true);
1751   if (ParenLevel != 0)
1752     return TokError("unbalanced parentheses in macro argument");
1753   return false;
1754 }
1755
1756 // Parse the macro instantiation arguments.
1757 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1758   const unsigned NParameters = M ? M->Parameters.size() : 0;
1759   // Argument delimiter is initially unknown. It will be set by
1760   // ParseMacroArgument()
1761   AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1762
1763   // Parse two kinds of macro invocations:
1764   // - macros defined without any parameters accept an arbitrary number of them
1765   // - macros defined with parameters accept at most that many of them
1766   for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1767        ++Parameter) {
1768     MacroArgument MA;
1769
1770     if (ParseMacroArgument(MA, ArgumentDelimiter))
1771       return true;
1772
1773     if (!MA.empty() || !NParameters)
1774       A.push_back(MA);
1775     else if (NParameters) {
1776       if (!M->Parameters[Parameter].second.empty())
1777         A.push_back(M->Parameters[Parameter].second);
1778     }
1779
1780     // At the end of the statement, fill in remaining arguments that have
1781     // default values. If there aren't any, then the next argument is
1782     // required but missing
1783     if (Lexer.is(AsmToken::EndOfStatement)) {
1784       if (NParameters && Parameter < NParameters - 1) {
1785         if (M->Parameters[Parameter + 1].second.empty())
1786           return TokError("macro argument '" +
1787                           Twine(M->Parameters[Parameter + 1].first) +
1788                           "' is missing");
1789         else
1790           continue;
1791       }
1792       return false;
1793     }
1794
1795     if (Lexer.is(AsmToken::Comma))
1796       Lex();
1797   }
1798   return TokError("Too many arguments");
1799 }
1800
1801 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1802                                  const Macro *M) {
1803   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1804   // this, although we should protect against infinite loops.
1805   if (ActiveMacros.size() == 20)
1806     return TokError("macros cannot be nested more than 20 levels deep");
1807
1808   MacroArguments A;
1809   if (ParseMacroArguments(M, A))
1810     return true;
1811
1812   // Remove any trailing empty arguments. Do this after-the-fact as we have
1813   // to keep empty arguments in the middle of the list or positionality
1814   // gets off. e.g.,  "foo 1, , 2" vs. "foo 1, 2,"
1815   while (!A.empty() && A.back().empty())
1816     A.pop_back();
1817
1818   // Macro instantiation is lexical, unfortunately. We construct a new buffer
1819   // to hold the macro body with substitutions.
1820   SmallString<256> Buf;
1821   StringRef Body = M->Body;
1822   raw_svector_ostream OS(Buf);
1823
1824   if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1825     return true;
1826
1827   // We include the .endmacro in the buffer as our queue to exit the macro
1828   // instantiation.
1829   OS << ".endmacro\n";
1830
1831   MemoryBuffer *Instantiation =
1832     MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1833
1834   // Create the macro instantiation object and add to the current macro
1835   // instantiation stack.
1836   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1837                                                   getTok().getLoc(),
1838                                                   Instantiation);
1839   ActiveMacros.push_back(MI);
1840
1841   // Jump to the macro instantiation and prime the lexer.
1842   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1843   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1844   Lex();
1845
1846   return false;
1847 }
1848
1849 void AsmParser::HandleMacroExit() {
1850   // Jump to the EndOfStatement we should return to, and consume it.
1851   JumpToLoc(ActiveMacros.back()->ExitLoc);
1852   Lex();
1853
1854   // Pop the instantiation entry.
1855   delete ActiveMacros.back();
1856   ActiveMacros.pop_back();
1857 }
1858
1859 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1860   switch (Value->getKind()) {
1861   case MCExpr::Binary: {
1862     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1863     return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1864     break;
1865   }
1866   case MCExpr::Target:
1867   case MCExpr::Constant:
1868     return false;
1869   case MCExpr::SymbolRef: {
1870     const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1871     if (S.isVariable())
1872       return IsUsedIn(Sym, S.getVariableValue());
1873     return &S == Sym;
1874   }
1875   case MCExpr::Unary:
1876     return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1877   }
1878
1879   llvm_unreachable("Unknown expr kind!");
1880 }
1881
1882 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1883                                 bool NoDeadStrip) {
1884   // FIXME: Use better location, we should use proper tokens.
1885   SMLoc EqualLoc = Lexer.getLoc();
1886
1887   const MCExpr *Value;
1888   if (ParseExpression(Value))
1889     return true;
1890
1891   // Note: we don't count b as used in "a = b". This is to allow
1892   // a = b
1893   // b = c
1894
1895   if (Lexer.isNot(AsmToken::EndOfStatement))
1896     return TokError("unexpected token in assignment");
1897
1898   // Error on assignment to '.'.
1899   if (Name == ".") {
1900     return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1901                             "(use '.space' or '.org').)"));
1902   }
1903
1904   // Eat the end of statement marker.
1905   Lex();
1906
1907   // Validate that the LHS is allowed to be a variable (either it has not been
1908   // used as a symbol, or it is an absolute symbol).
1909   MCSymbol *Sym = getContext().LookupSymbol(Name);
1910   if (Sym) {
1911     // Diagnose assignment to a label.
1912     //
1913     // FIXME: Diagnostics. Note the location of the definition as a label.
1914     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1915     if (IsUsedIn(Sym, Value))
1916       return Error(EqualLoc, "Recursive use of '" + Name + "'");
1917     else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1918       ; // Allow redefinitions of undefined symbols only used in directives.
1919     else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1920       ; // Allow redefinitions of variables that haven't yet been used.
1921     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1922       return Error(EqualLoc, "redefinition of '" + Name + "'");
1923     else if (!Sym->isVariable())
1924       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1925     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1926       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1927                    Name + "'");
1928
1929     // Don't count these checks as uses.
1930     Sym->setUsed(false);
1931   } else
1932     Sym = getContext().GetOrCreateSymbol(Name);
1933
1934   // FIXME: Handle '.'.
1935
1936   // Do the assignment.
1937   Out.EmitAssignment(Sym, Value);
1938   if (NoDeadStrip)
1939     Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1940
1941
1942   return false;
1943 }
1944
1945 /// ParseIdentifier:
1946 ///   ::= identifier
1947 ///   ::= string
1948 bool AsmParser::ParseIdentifier(StringRef &Res) {
1949   // The assembler has relaxed rules for accepting identifiers, in particular we
1950   // allow things like '.globl $foo', which would normally be separate
1951   // tokens. At this level, we have already lexed so we cannot (currently)
1952   // handle this as a context dependent token, instead we detect adjacent tokens
1953   // and return the combined identifier.
1954   if (Lexer.is(AsmToken::Dollar)) {
1955     SMLoc DollarLoc = getLexer().getLoc();
1956
1957     // Consume the dollar sign, and check for a following identifier.
1958     Lex();
1959     if (Lexer.isNot(AsmToken::Identifier))
1960       return true;
1961
1962     // We have a '$' followed by an identifier, make sure they are adjacent.
1963     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1964       return true;
1965
1966     // Construct the joined identifier and consume the token.
1967     Res = StringRef(DollarLoc.getPointer(),
1968                     getTok().getIdentifier().size() + 1);
1969     Lex();
1970     return false;
1971   }
1972
1973   if (Lexer.isNot(AsmToken::Identifier) &&
1974       Lexer.isNot(AsmToken::String))
1975     return true;
1976
1977   Res = getTok().getIdentifier();
1978
1979   Lex(); // Consume the identifier token.
1980
1981   return false;
1982 }
1983
1984 /// ParseDirectiveSet:
1985 ///   ::= .equ identifier ',' expression
1986 ///   ::= .equiv identifier ',' expression
1987 ///   ::= .set identifier ',' expression
1988 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1989   StringRef Name;
1990
1991   if (ParseIdentifier(Name))
1992     return TokError("expected identifier after '" + Twine(IDVal) + "'");
1993
1994   if (getLexer().isNot(AsmToken::Comma))
1995     return TokError("unexpected token in '" + Twine(IDVal) + "'");
1996   Lex();
1997
1998   return ParseAssignment(Name, allow_redef, true);
1999 }
2000
2001 bool AsmParser::ParseEscapedString(std::string &Data) {
2002   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2003
2004   Data = "";
2005   StringRef Str = getTok().getStringContents();
2006   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2007     if (Str[i] != '\\') {
2008       Data += Str[i];
2009       continue;
2010     }
2011
2012     // Recognize escaped characters. Note that this escape semantics currently
2013     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2014     ++i;
2015     if (i == e)
2016       return TokError("unexpected backslash at end of string");
2017
2018     // Recognize octal sequences.
2019     if ((unsigned) (Str[i] - '0') <= 7) {
2020       // Consume up to three octal characters.
2021       unsigned Value = Str[i] - '0';
2022
2023       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2024         ++i;
2025         Value = Value * 8 + (Str[i] - '0');
2026
2027         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2028           ++i;
2029           Value = Value * 8 + (Str[i] - '0');
2030         }
2031       }
2032
2033       if (Value > 255)
2034         return TokError("invalid octal escape sequence (out of range)");
2035
2036       Data += (unsigned char) Value;
2037       continue;
2038     }
2039
2040     // Otherwise recognize individual escapes.
2041     switch (Str[i]) {
2042     default:
2043       // Just reject invalid escape sequences for now.
2044       return TokError("invalid escape sequence (unrecognized character)");
2045
2046     case 'b': Data += '\b'; break;
2047     case 'f': Data += '\f'; break;
2048     case 'n': Data += '\n'; break;
2049     case 'r': Data += '\r'; break;
2050     case 't': Data += '\t'; break;
2051     case '"': Data += '"'; break;
2052     case '\\': Data += '\\'; break;
2053     }
2054   }
2055
2056   return false;
2057 }
2058
2059 /// ParseDirectiveAscii:
2060 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2061 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2062   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2063     CheckForValidSection();
2064
2065     for (;;) {
2066       if (getLexer().isNot(AsmToken::String))
2067         return TokError("expected string in '" + Twine(IDVal) + "' directive");
2068
2069       std::string Data;
2070       if (ParseEscapedString(Data))
2071         return true;
2072
2073       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2074       if (ZeroTerminated)
2075         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2076
2077       Lex();
2078
2079       if (getLexer().is(AsmToken::EndOfStatement))
2080         break;
2081
2082       if (getLexer().isNot(AsmToken::Comma))
2083         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2084       Lex();
2085     }
2086   }
2087
2088   Lex();
2089   return false;
2090 }
2091
2092 /// ParseDirectiveValue
2093 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
2094 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2095   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2096     CheckForValidSection();
2097
2098     for (;;) {
2099       const MCExpr *Value;
2100       SMLoc ExprLoc = getLexer().getLoc();
2101       if (ParseExpression(Value))
2102         return true;
2103
2104       // Special case constant expressions to match code generator.
2105       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2106         assert(Size <= 8 && "Invalid size");
2107         uint64_t IntValue = MCE->getValue();
2108         if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2109           return Error(ExprLoc, "literal value out of range for directive");
2110         getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2111       } else
2112         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2113
2114       if (getLexer().is(AsmToken::EndOfStatement))
2115         break;
2116
2117       // FIXME: Improve diagnostic.
2118       if (getLexer().isNot(AsmToken::Comma))
2119         return TokError("unexpected token in directive");
2120       Lex();
2121     }
2122   }
2123
2124   Lex();
2125   return false;
2126 }
2127
2128 /// ParseDirectiveRealValue
2129 ///  ::= (.single | .double) [ expression (, expression)* ]
2130 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2131   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2132     CheckForValidSection();
2133
2134     for (;;) {
2135       // We don't truly support arithmetic on floating point expressions, so we
2136       // have to manually parse unary prefixes.
2137       bool IsNeg = false;
2138       if (getLexer().is(AsmToken::Minus)) {
2139         Lex();
2140         IsNeg = true;
2141       } else if (getLexer().is(AsmToken::Plus))
2142         Lex();
2143
2144       if (getLexer().isNot(AsmToken::Integer) &&
2145           getLexer().isNot(AsmToken::Real) &&
2146           getLexer().isNot(AsmToken::Identifier))
2147         return TokError("unexpected token in directive");
2148
2149       // Convert to an APFloat.
2150       APFloat Value(Semantics);
2151       StringRef IDVal = getTok().getString();
2152       if (getLexer().is(AsmToken::Identifier)) {
2153         if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2154           Value = APFloat::getInf(Semantics);
2155         else if (!IDVal.compare_lower("nan"))
2156           Value = APFloat::getNaN(Semantics, false, ~0);
2157         else
2158           return TokError("invalid floating point literal");
2159       } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2160           APFloat::opInvalidOp)
2161         return TokError("invalid floating point literal");
2162       if (IsNeg)
2163         Value.changeSign();
2164
2165       // Consume the numeric token.
2166       Lex();
2167
2168       // Emit the value as an integer.
2169       APInt AsInt = Value.bitcastToAPInt();
2170       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2171                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2172
2173       if (getLexer().is(AsmToken::EndOfStatement))
2174         break;
2175
2176       if (getLexer().isNot(AsmToken::Comma))
2177         return TokError("unexpected token in directive");
2178       Lex();
2179     }
2180   }
2181
2182   Lex();
2183   return false;
2184 }
2185
2186 /// ParseDirectiveSpace
2187 ///  ::= .space expression [ , expression ]
2188 bool AsmParser::ParseDirectiveSpace() {
2189   CheckForValidSection();
2190
2191   int64_t NumBytes;
2192   if (ParseAbsoluteExpression(NumBytes))
2193     return true;
2194
2195   int64_t FillExpr = 0;
2196   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2197     if (getLexer().isNot(AsmToken::Comma))
2198       return TokError("unexpected token in '.space' directive");
2199     Lex();
2200
2201     if (ParseAbsoluteExpression(FillExpr))
2202       return true;
2203
2204     if (getLexer().isNot(AsmToken::EndOfStatement))
2205       return TokError("unexpected token in '.space' directive");
2206   }
2207
2208   Lex();
2209
2210   if (NumBytes <= 0)
2211     return TokError("invalid number of bytes in '.space' directive");
2212
2213   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2214   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2215
2216   return false;
2217 }
2218
2219 /// ParseDirectiveZero
2220 ///  ::= .zero expression
2221 bool AsmParser::ParseDirectiveZero() {
2222   CheckForValidSection();
2223
2224   int64_t NumBytes;
2225   if (ParseAbsoluteExpression(NumBytes))
2226     return true;
2227
2228   int64_t Val = 0;
2229   if (getLexer().is(AsmToken::Comma)) {
2230     Lex();
2231     if (ParseAbsoluteExpression(Val))
2232       return true;
2233   }
2234
2235   if (getLexer().isNot(AsmToken::EndOfStatement))
2236     return TokError("unexpected token in '.zero' directive");
2237
2238   Lex();
2239
2240   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2241
2242   return false;
2243 }
2244
2245 /// ParseDirectiveFill
2246 ///  ::= .fill expression , expression , expression
2247 bool AsmParser::ParseDirectiveFill() {
2248   CheckForValidSection();
2249
2250   int64_t NumValues;
2251   if (ParseAbsoluteExpression(NumValues))
2252     return true;
2253
2254   if (getLexer().isNot(AsmToken::Comma))
2255     return TokError("unexpected token in '.fill' directive");
2256   Lex();
2257
2258   int64_t FillSize;
2259   if (ParseAbsoluteExpression(FillSize))
2260     return true;
2261
2262   if (getLexer().isNot(AsmToken::Comma))
2263     return TokError("unexpected token in '.fill' directive");
2264   Lex();
2265
2266   int64_t FillExpr;
2267   if (ParseAbsoluteExpression(FillExpr))
2268     return true;
2269
2270   if (getLexer().isNot(AsmToken::EndOfStatement))
2271     return TokError("unexpected token in '.fill' directive");
2272
2273   Lex();
2274
2275   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2276     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2277
2278   for (uint64_t i = 0, e = NumValues; i != e; ++i)
2279     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2280
2281   return false;
2282 }
2283
2284 /// ParseDirectiveOrg
2285 ///  ::= .org expression [ , expression ]
2286 bool AsmParser::ParseDirectiveOrg() {
2287   CheckForValidSection();
2288
2289   const MCExpr *Offset;
2290   SMLoc Loc = getTok().getLoc();
2291   if (ParseExpression(Offset))
2292     return true;
2293
2294   // Parse optional fill expression.
2295   int64_t FillExpr = 0;
2296   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2297     if (getLexer().isNot(AsmToken::Comma))
2298       return TokError("unexpected token in '.org' directive");
2299     Lex();
2300
2301     if (ParseAbsoluteExpression(FillExpr))
2302       return true;
2303
2304     if (getLexer().isNot(AsmToken::EndOfStatement))
2305       return TokError("unexpected token in '.org' directive");
2306   }
2307
2308   Lex();
2309
2310   // Only limited forms of relocatable expressions are accepted here, it
2311   // has to be relative to the current section. The streamer will return
2312   // 'true' if the expression wasn't evaluatable.
2313   if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2314     return Error(Loc, "expected assembly-time absolute expression");
2315
2316   return false;
2317 }
2318
2319 /// ParseDirectiveAlign
2320 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
2321 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2322   CheckForValidSection();
2323
2324   SMLoc AlignmentLoc = getLexer().getLoc();
2325   int64_t Alignment;
2326   if (ParseAbsoluteExpression(Alignment))
2327     return true;
2328
2329   SMLoc MaxBytesLoc;
2330   bool HasFillExpr = false;
2331   int64_t FillExpr = 0;
2332   int64_t MaxBytesToFill = 0;
2333   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2334     if (getLexer().isNot(AsmToken::Comma))
2335       return TokError("unexpected token in directive");
2336     Lex();
2337
2338     // The fill expression can be omitted while specifying a maximum number of
2339     // alignment bytes, e.g:
2340     //  .align 3,,4
2341     if (getLexer().isNot(AsmToken::Comma)) {
2342       HasFillExpr = true;
2343       if (ParseAbsoluteExpression(FillExpr))
2344         return true;
2345     }
2346
2347     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2348       if (getLexer().isNot(AsmToken::Comma))
2349         return TokError("unexpected token in directive");
2350       Lex();
2351
2352       MaxBytesLoc = getLexer().getLoc();
2353       if (ParseAbsoluteExpression(MaxBytesToFill))
2354         return true;
2355
2356       if (getLexer().isNot(AsmToken::EndOfStatement))
2357         return TokError("unexpected token in directive");
2358     }
2359   }
2360
2361   Lex();
2362
2363   if (!HasFillExpr)
2364     FillExpr = 0;
2365
2366   // Compute alignment in bytes.
2367   if (IsPow2) {
2368     // FIXME: Diagnose overflow.
2369     if (Alignment >= 32) {
2370       Error(AlignmentLoc, "invalid alignment value");
2371       Alignment = 31;
2372     }
2373
2374     Alignment = 1ULL << Alignment;
2375   }
2376
2377   // Diagnose non-sensical max bytes to align.
2378   if (MaxBytesLoc.isValid()) {
2379     if (MaxBytesToFill < 1) {
2380       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2381             "many bytes, ignoring maximum bytes expression");
2382       MaxBytesToFill = 0;
2383     }
2384
2385     if (MaxBytesToFill >= Alignment) {
2386       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2387               "has no effect");
2388       MaxBytesToFill = 0;
2389     }
2390   }
2391
2392   // Check whether we should use optimal code alignment for this .align
2393   // directive.
2394   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2395   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2396       ValueSize == 1 && UseCodeAlign) {
2397     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2398   } else {
2399     // FIXME: Target specific behavior about how the "extra" bytes are filled.
2400     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2401                                        MaxBytesToFill);
2402   }
2403
2404   return false;
2405 }
2406
2407 /// ParseDirectiveSymbolAttribute
2408 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2409 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2410   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2411     for (;;) {
2412       StringRef Name;
2413       SMLoc Loc = getTok().getLoc();
2414
2415       if (ParseIdentifier(Name))
2416         return Error(Loc, "expected identifier in directive");
2417
2418       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2419
2420       // Assembler local symbols don't make any sense here. Complain loudly.
2421       if (Sym->isTemporary())
2422         return Error(Loc, "non-local symbol required in directive");
2423
2424       getStreamer().EmitSymbolAttribute(Sym, Attr);
2425
2426       if (getLexer().is(AsmToken::EndOfStatement))
2427         break;
2428
2429       if (getLexer().isNot(AsmToken::Comma))
2430         return TokError("unexpected token in directive");
2431       Lex();
2432     }
2433   }
2434
2435   Lex();
2436   return false;
2437 }
2438
2439 /// ParseDirectiveComm
2440 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2441 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2442   CheckForValidSection();
2443
2444   SMLoc IDLoc = getLexer().getLoc();
2445   StringRef Name;
2446   if (ParseIdentifier(Name))
2447     return TokError("expected identifier in directive");
2448
2449   // Handle the identifier as the key symbol.
2450   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2451
2452   if (getLexer().isNot(AsmToken::Comma))
2453     return TokError("unexpected token in directive");
2454   Lex();
2455
2456   int64_t Size;
2457   SMLoc SizeLoc = getLexer().getLoc();
2458   if (ParseAbsoluteExpression(Size))
2459     return true;
2460
2461   int64_t Pow2Alignment = 0;
2462   SMLoc Pow2AlignmentLoc;
2463   if (getLexer().is(AsmToken::Comma)) {
2464     Lex();
2465     Pow2AlignmentLoc = getLexer().getLoc();
2466     if (ParseAbsoluteExpression(Pow2Alignment))
2467       return true;
2468
2469     LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2470     if (IsLocal && LCOMM == LCOMM::NoAlignment)
2471       return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2472
2473     // If this target takes alignments in bytes (not log) validate and convert.
2474     if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2475         (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2476       if (!isPowerOf2_64(Pow2Alignment))
2477         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2478       Pow2Alignment = Log2_64(Pow2Alignment);
2479     }
2480   }
2481
2482   if (getLexer().isNot(AsmToken::EndOfStatement))
2483     return TokError("unexpected token in '.comm' or '.lcomm' directive");
2484
2485   Lex();
2486
2487   // NOTE: a size of zero for a .comm should create a undefined symbol
2488   // but a size of .lcomm creates a bss symbol of size zero.
2489   if (Size < 0)
2490     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2491                  "be less than zero");
2492
2493   // NOTE: The alignment in the directive is a power of 2 value, the assembler
2494   // may internally end up wanting an alignment in bytes.
2495   // FIXME: Diagnose overflow.
2496   if (Pow2Alignment < 0)
2497     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2498                  "alignment, can't be less than zero");
2499
2500   if (!Sym->isUndefined())
2501     return Error(IDLoc, "invalid symbol redefinition");
2502
2503   // Create the Symbol as a common or local common with Size and Pow2Alignment
2504   if (IsLocal) {
2505     getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2506     return false;
2507   }
2508
2509   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2510   return false;
2511 }
2512
2513 /// ParseDirectiveAbort
2514 ///  ::= .abort [... message ...]
2515 bool AsmParser::ParseDirectiveAbort() {
2516   // FIXME: Use loc from directive.
2517   SMLoc Loc = getLexer().getLoc();
2518
2519   StringRef Str = ParseStringToEndOfStatement();
2520   if (getLexer().isNot(AsmToken::EndOfStatement))
2521     return TokError("unexpected token in '.abort' directive");
2522
2523   Lex();
2524
2525   if (Str.empty())
2526     Error(Loc, ".abort detected. Assembly stopping.");
2527   else
2528     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2529   // FIXME: Actually abort assembly here.
2530
2531   return false;
2532 }
2533
2534 /// ParseDirectiveInclude
2535 ///  ::= .include "filename"
2536 bool AsmParser::ParseDirectiveInclude() {
2537   if (getLexer().isNot(AsmToken::String))
2538     return TokError("expected string in '.include' directive");
2539
2540   std::string Filename = getTok().getString();
2541   SMLoc IncludeLoc = getLexer().getLoc();
2542   Lex();
2543
2544   if (getLexer().isNot(AsmToken::EndOfStatement))
2545     return TokError("unexpected token in '.include' directive");
2546
2547   // Strip the quotes.
2548   Filename = Filename.substr(1, Filename.size()-2);
2549
2550   // Attempt to switch the lexer to the included file before consuming the end
2551   // of statement to avoid losing it when we switch.
2552   if (EnterIncludeFile(Filename)) {
2553     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2554     return true;
2555   }
2556
2557   return false;
2558 }
2559
2560 /// ParseDirectiveIncbin
2561 ///  ::= .incbin "filename"
2562 bool AsmParser::ParseDirectiveIncbin() {
2563   if (getLexer().isNot(AsmToken::String))
2564     return TokError("expected string in '.incbin' directive");
2565
2566   std::string Filename = getTok().getString();
2567   SMLoc IncbinLoc = getLexer().getLoc();
2568   Lex();
2569
2570   if (getLexer().isNot(AsmToken::EndOfStatement))
2571     return TokError("unexpected token in '.incbin' directive");
2572
2573   // Strip the quotes.
2574   Filename = Filename.substr(1, Filename.size()-2);
2575
2576   // Attempt to process the included file.
2577   if (ProcessIncbinFile(Filename)) {
2578     Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2579     return true;
2580   }
2581
2582   return false;
2583 }
2584
2585 /// ParseDirectiveIf
2586 /// ::= .if expression
2587 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2588   TheCondStack.push_back(TheCondState);
2589   TheCondState.TheCond = AsmCond::IfCond;
2590   if (TheCondState.Ignore) {
2591     EatToEndOfStatement();
2592   } else {
2593     int64_t ExprValue;
2594     if (ParseAbsoluteExpression(ExprValue))
2595       return true;
2596
2597     if (getLexer().isNot(AsmToken::EndOfStatement))
2598       return TokError("unexpected token in '.if' directive");
2599
2600     Lex();
2601
2602     TheCondState.CondMet = ExprValue;
2603     TheCondState.Ignore = !TheCondState.CondMet;
2604   }
2605
2606   return false;
2607 }
2608
2609 /// ParseDirectiveIfb
2610 /// ::= .ifb string
2611 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2612   TheCondStack.push_back(TheCondState);
2613   TheCondState.TheCond = AsmCond::IfCond;
2614
2615   if (TheCondState.Ignore) {
2616     EatToEndOfStatement();
2617   } else {
2618     StringRef Str = ParseStringToEndOfStatement();
2619
2620     if (getLexer().isNot(AsmToken::EndOfStatement))
2621       return TokError("unexpected token in '.ifb' directive");
2622
2623     Lex();
2624
2625     TheCondState.CondMet = ExpectBlank == Str.empty();
2626     TheCondState.Ignore = !TheCondState.CondMet;
2627   }
2628
2629   return false;
2630 }
2631
2632 /// ParseDirectiveIfc
2633 /// ::= .ifc string1, string2
2634 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2635   TheCondStack.push_back(TheCondState);
2636   TheCondState.TheCond = AsmCond::IfCond;
2637
2638   if (TheCondState.Ignore) {
2639     EatToEndOfStatement();
2640   } else {
2641     StringRef Str1 = ParseStringToComma();
2642
2643     if (getLexer().isNot(AsmToken::Comma))
2644       return TokError("unexpected token in '.ifc' directive");
2645
2646     Lex();
2647
2648     StringRef Str2 = ParseStringToEndOfStatement();
2649
2650     if (getLexer().isNot(AsmToken::EndOfStatement))
2651       return TokError("unexpected token in '.ifc' directive");
2652
2653     Lex();
2654
2655     TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2656     TheCondState.Ignore = !TheCondState.CondMet;
2657   }
2658
2659   return false;
2660 }
2661
2662 /// ParseDirectiveIfdef
2663 /// ::= .ifdef symbol
2664 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2665   StringRef Name;
2666   TheCondStack.push_back(TheCondState);
2667   TheCondState.TheCond = AsmCond::IfCond;
2668
2669   if (TheCondState.Ignore) {
2670     EatToEndOfStatement();
2671   } else {
2672     if (ParseIdentifier(Name))
2673       return TokError("expected identifier after '.ifdef'");
2674
2675     Lex();
2676
2677     MCSymbol *Sym = getContext().LookupSymbol(Name);
2678
2679     if (expect_defined)
2680       TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2681     else
2682       TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2683     TheCondState.Ignore = !TheCondState.CondMet;
2684   }
2685
2686   return false;
2687 }
2688
2689 /// ParseDirectiveElseIf
2690 /// ::= .elseif expression
2691 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2692   if (TheCondState.TheCond != AsmCond::IfCond &&
2693       TheCondState.TheCond != AsmCond::ElseIfCond)
2694       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2695                           " an .elseif");
2696   TheCondState.TheCond = AsmCond::ElseIfCond;
2697
2698   bool LastIgnoreState = false;
2699   if (!TheCondStack.empty())
2700       LastIgnoreState = TheCondStack.back().Ignore;
2701   if (LastIgnoreState || TheCondState.CondMet) {
2702     TheCondState.Ignore = true;
2703     EatToEndOfStatement();
2704   }
2705   else {
2706     int64_t ExprValue;
2707     if (ParseAbsoluteExpression(ExprValue))
2708       return true;
2709
2710     if (getLexer().isNot(AsmToken::EndOfStatement))
2711       return TokError("unexpected token in '.elseif' directive");
2712
2713     Lex();
2714     TheCondState.CondMet = ExprValue;
2715     TheCondState.Ignore = !TheCondState.CondMet;
2716   }
2717
2718   return false;
2719 }
2720
2721 /// ParseDirectiveElse
2722 /// ::= .else
2723 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2724   if (getLexer().isNot(AsmToken::EndOfStatement))
2725     return TokError("unexpected token in '.else' directive");
2726
2727   Lex();
2728
2729   if (TheCondState.TheCond != AsmCond::IfCond &&
2730       TheCondState.TheCond != AsmCond::ElseIfCond)
2731       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2732                           ".elseif");
2733   TheCondState.TheCond = AsmCond::ElseCond;
2734   bool LastIgnoreState = false;
2735   if (!TheCondStack.empty())
2736     LastIgnoreState = TheCondStack.back().Ignore;
2737   if (LastIgnoreState || TheCondState.CondMet)
2738     TheCondState.Ignore = true;
2739   else
2740     TheCondState.Ignore = false;
2741
2742   return false;
2743 }
2744
2745 /// ParseDirectiveEndIf
2746 /// ::= .endif
2747 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2748   if (getLexer().isNot(AsmToken::EndOfStatement))
2749     return TokError("unexpected token in '.endif' directive");
2750
2751   Lex();
2752
2753   if ((TheCondState.TheCond == AsmCond::NoCond) ||
2754       TheCondStack.empty())
2755     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2756                         ".else");
2757   if (!TheCondStack.empty()) {
2758     TheCondState = TheCondStack.back();
2759     TheCondStack.pop_back();
2760   }
2761
2762   return false;
2763 }
2764
2765 /// ParseDirectiveFile
2766 /// ::= .file [number] filename
2767 /// ::= .file number directory filename
2768 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2769   // FIXME: I'm not sure what this is.
2770   int64_t FileNumber = -1;
2771   SMLoc FileNumberLoc = getLexer().getLoc();
2772   if (getLexer().is(AsmToken::Integer)) {
2773     FileNumber = getTok().getIntVal();
2774     Lex();
2775
2776     if (FileNumber < 1)
2777       return TokError("file number less than one");
2778   }
2779
2780   if (getLexer().isNot(AsmToken::String))
2781     return TokError("unexpected token in '.file' directive");
2782
2783   // Usually the directory and filename together, otherwise just the directory.
2784   StringRef Path = getTok().getString();
2785   Path = Path.substr(1, Path.size()-2);
2786   Lex();
2787
2788   StringRef Directory;
2789   StringRef Filename;
2790   if (getLexer().is(AsmToken::String)) {
2791     if (FileNumber == -1)
2792       return TokError("explicit path specified, but no file number");
2793     Filename = getTok().getString();
2794     Filename = Filename.substr(1, Filename.size()-2);
2795     Directory = Path;
2796     Lex();
2797   } else {
2798     Filename = Path;
2799   }
2800
2801   if (getLexer().isNot(AsmToken::EndOfStatement))
2802     return TokError("unexpected token in '.file' directive");
2803
2804   if (FileNumber == -1)
2805     getStreamer().EmitFileDirective(Filename);
2806   else {
2807     if (getContext().getGenDwarfForAssembly() == true)
2808       Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2809                         "used to generate dwarf debug info for assembly code");
2810
2811     if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2812       Error(FileNumberLoc, "file number already allocated");
2813   }
2814
2815   return false;
2816 }
2817
2818 /// ParseDirectiveLine
2819 /// ::= .line [number]
2820 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2821   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2822     if (getLexer().isNot(AsmToken::Integer))
2823       return TokError("unexpected token in '.line' directive");
2824
2825     int64_t LineNumber = getTok().getIntVal();
2826     (void) LineNumber;
2827     Lex();
2828
2829     // FIXME: Do something with the .line.
2830   }
2831
2832   if (getLexer().isNot(AsmToken::EndOfStatement))
2833     return TokError("unexpected token in '.line' directive");
2834
2835   return false;
2836 }
2837
2838
2839 /// ParseDirectiveLoc
2840 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2841 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2842 /// The first number is a file number, must have been previously assigned with
2843 /// a .file directive, the second number is the line number and optionally the
2844 /// third number is a column position (zero if not specified).  The remaining
2845 /// optional items are .loc sub-directives.
2846 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2847
2848   if (getLexer().isNot(AsmToken::Integer))
2849     return TokError("unexpected token in '.loc' directive");
2850   int64_t FileNumber = getTok().getIntVal();
2851   if (FileNumber < 1)
2852     return TokError("file number less than one in '.loc' directive");
2853   if (!getContext().isValidDwarfFileNumber(FileNumber))
2854     return TokError("unassigned file number in '.loc' directive");
2855   Lex();
2856
2857   int64_t LineNumber = 0;
2858   if (getLexer().is(AsmToken::Integer)) {
2859     LineNumber = getTok().getIntVal();
2860     if (LineNumber < 1)
2861       return TokError("line number less than one in '.loc' directive");
2862     Lex();
2863   }
2864
2865   int64_t ColumnPos = 0;
2866   if (getLexer().is(AsmToken::Integer)) {
2867     ColumnPos = getTok().getIntVal();
2868     if (ColumnPos < 0)
2869       return TokError("column position less than zero in '.loc' directive");
2870     Lex();
2871   }
2872
2873   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2874   unsigned Isa = 0;
2875   int64_t Discriminator = 0;
2876   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2877     for (;;) {
2878       if (getLexer().is(AsmToken::EndOfStatement))
2879         break;
2880
2881       StringRef Name;
2882       SMLoc Loc = getTok().getLoc();
2883       if (getParser().ParseIdentifier(Name))
2884         return TokError("unexpected token in '.loc' directive");
2885
2886       if (Name == "basic_block")
2887         Flags |= DWARF2_FLAG_BASIC_BLOCK;
2888       else if (Name == "prologue_end")
2889         Flags |= DWARF2_FLAG_PROLOGUE_END;
2890       else if (Name == "epilogue_begin")
2891         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2892       else if (Name == "is_stmt") {
2893         SMLoc Loc = getTok().getLoc();
2894         const MCExpr *Value;
2895         if (getParser().ParseExpression(Value))
2896           return true;
2897         // The expression must be the constant 0 or 1.
2898         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2899           int Value = MCE->getValue();
2900           if (Value == 0)
2901             Flags &= ~DWARF2_FLAG_IS_STMT;
2902           else if (Value == 1)
2903             Flags |= DWARF2_FLAG_IS_STMT;
2904           else
2905             return Error(Loc, "is_stmt value not 0 or 1");
2906         }
2907         else {
2908           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2909         }
2910       }
2911       else if (Name == "isa") {
2912         SMLoc Loc = getTok().getLoc();
2913         const MCExpr *Value;
2914         if (getParser().ParseExpression(Value))
2915           return true;
2916         // The expression must be a constant greater or equal to 0.
2917         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2918           int Value = MCE->getValue();
2919           if (Value < 0)
2920             return Error(Loc, "isa number less than zero");
2921           Isa = Value;
2922         }
2923         else {
2924           return Error(Loc, "isa number not a constant value");
2925         }
2926       }
2927       else if (Name == "discriminator") {
2928         if (getParser().ParseAbsoluteExpression(Discriminator))
2929           return true;
2930       }
2931       else {
2932         return Error(Loc, "unknown sub-directive in '.loc' directive");
2933       }
2934
2935       if (getLexer().is(AsmToken::EndOfStatement))
2936         break;
2937     }
2938   }
2939
2940   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2941                                       Isa, Discriminator, StringRef());
2942
2943   return false;
2944 }
2945
2946 /// ParseDirectiveStabs
2947 /// ::= .stabs string, number, number, number
2948 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2949                                            SMLoc DirectiveLoc) {
2950   return TokError("unsupported directive '" + Directive + "'");
2951 }
2952
2953 /// ParseDirectiveCFISections
2954 /// ::= .cfi_sections section [, section]
2955 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2956                                                  SMLoc DirectiveLoc) {
2957   StringRef Name;
2958   bool EH = false;
2959   bool Debug = false;
2960
2961   if (getParser().ParseIdentifier(Name))
2962     return TokError("Expected an identifier");
2963
2964   if (Name == ".eh_frame")
2965     EH = true;
2966   else if (Name == ".debug_frame")
2967     Debug = true;
2968
2969   if (getLexer().is(AsmToken::Comma)) {
2970     Lex();
2971
2972     if (getParser().ParseIdentifier(Name))
2973       return TokError("Expected an identifier");
2974
2975     if (Name == ".eh_frame")
2976       EH = true;
2977     else if (Name == ".debug_frame")
2978       Debug = true;
2979   }
2980
2981   getStreamer().EmitCFISections(EH, Debug);
2982
2983   return false;
2984 }
2985
2986 /// ParseDirectiveCFIStartProc
2987 /// ::= .cfi_startproc
2988 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2989                                                   SMLoc DirectiveLoc) {
2990   getStreamer().EmitCFIStartProc();
2991   return false;
2992 }
2993
2994 /// ParseDirectiveCFIEndProc
2995 /// ::= .cfi_endproc
2996 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2997   getStreamer().EmitCFIEndProc();
2998   return false;
2999 }
3000
3001 /// ParseRegisterOrRegisterNumber - parse register name or number.
3002 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3003                                                      SMLoc DirectiveLoc) {
3004   unsigned RegNo;
3005
3006   if (getLexer().isNot(AsmToken::Integer)) {
3007     if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3008       DirectiveLoc))
3009       return true;
3010     Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3011   } else
3012     return getParser().ParseAbsoluteExpression(Register);
3013
3014   return false;
3015 }
3016
3017 /// ParseDirectiveCFIDefCfa
3018 /// ::= .cfi_def_cfa register,  offset
3019 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3020                                                SMLoc DirectiveLoc) {
3021   int64_t Register = 0;
3022   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3023     return true;
3024
3025   if (getLexer().isNot(AsmToken::Comma))
3026     return TokError("unexpected token in directive");
3027   Lex();
3028
3029   int64_t Offset = 0;
3030   if (getParser().ParseAbsoluteExpression(Offset))
3031     return true;
3032
3033   getStreamer().EmitCFIDefCfa(Register, Offset);
3034   return false;
3035 }
3036
3037 /// ParseDirectiveCFIDefCfaOffset
3038 /// ::= .cfi_def_cfa_offset offset
3039 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3040                                                      SMLoc DirectiveLoc) {
3041   int64_t Offset = 0;
3042   if (getParser().ParseAbsoluteExpression(Offset))
3043     return true;
3044
3045   getStreamer().EmitCFIDefCfaOffset(Offset);
3046   return false;
3047 }
3048
3049 /// ParseDirectiveCFIAdjustCfaOffset
3050 /// ::= .cfi_adjust_cfa_offset adjustment
3051 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3052                                                         SMLoc DirectiveLoc) {
3053   int64_t Adjustment = 0;
3054   if (getParser().ParseAbsoluteExpression(Adjustment))
3055     return true;
3056
3057   getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3058   return false;
3059 }
3060
3061 /// ParseDirectiveCFIDefCfaRegister
3062 /// ::= .cfi_def_cfa_register register
3063 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3064                                                        SMLoc DirectiveLoc) {
3065   int64_t Register = 0;
3066   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3067     return true;
3068
3069   getStreamer().EmitCFIDefCfaRegister(Register);
3070   return false;
3071 }
3072
3073 /// ParseDirectiveCFIOffset
3074 /// ::= .cfi_offset register, offset
3075 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3076   int64_t Register = 0;
3077   int64_t Offset = 0;
3078
3079   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3080     return true;
3081
3082   if (getLexer().isNot(AsmToken::Comma))
3083     return TokError("unexpected token in directive");
3084   Lex();
3085
3086   if (getParser().ParseAbsoluteExpression(Offset))
3087     return true;
3088
3089   getStreamer().EmitCFIOffset(Register, Offset);
3090   return false;
3091 }
3092
3093 /// ParseDirectiveCFIRelOffset
3094 /// ::= .cfi_rel_offset register, offset
3095 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3096                                                   SMLoc DirectiveLoc) {
3097   int64_t Register = 0;
3098
3099   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3100     return true;
3101
3102   if (getLexer().isNot(AsmToken::Comma))
3103     return TokError("unexpected token in directive");
3104   Lex();
3105
3106   int64_t Offset = 0;
3107   if (getParser().ParseAbsoluteExpression(Offset))
3108     return true;
3109
3110   getStreamer().EmitCFIRelOffset(Register, Offset);
3111   return false;
3112 }
3113
3114 static bool isValidEncoding(int64_t Encoding) {
3115   if (Encoding & ~0xff)
3116     return false;
3117
3118   if (Encoding == dwarf::DW_EH_PE_omit)
3119     return true;
3120
3121   const unsigned Format = Encoding & 0xf;
3122   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3123       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3124       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3125       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3126     return false;
3127
3128   const unsigned Application = Encoding & 0x70;
3129   if (Application != dwarf::DW_EH_PE_absptr &&
3130       Application != dwarf::DW_EH_PE_pcrel)
3131     return false;
3132
3133   return true;
3134 }
3135
3136 /// ParseDirectiveCFIPersonalityOrLsda
3137 /// ::= .cfi_personality encoding, [symbol_name]
3138 /// ::= .cfi_lsda encoding, [symbol_name]
3139 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3140                                                     SMLoc DirectiveLoc) {
3141   int64_t Encoding = 0;
3142   if (getParser().ParseAbsoluteExpression(Encoding))
3143     return true;
3144   if (Encoding == dwarf::DW_EH_PE_omit)
3145     return false;
3146
3147   if (!isValidEncoding(Encoding))
3148     return TokError("unsupported encoding.");
3149
3150   if (getLexer().isNot(AsmToken::Comma))
3151     return TokError("unexpected token in directive");
3152   Lex();
3153
3154   StringRef Name;
3155   if (getParser().ParseIdentifier(Name))
3156     return TokError("expected identifier in directive");
3157
3158   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3159
3160   if (IDVal == ".cfi_personality")
3161     getStreamer().EmitCFIPersonality(Sym, Encoding);
3162   else {
3163     assert(IDVal == ".cfi_lsda");
3164     getStreamer().EmitCFILsda(Sym, Encoding);
3165   }
3166   return false;
3167 }
3168
3169 /// ParseDirectiveCFIRememberState
3170 /// ::= .cfi_remember_state
3171 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3172                                                       SMLoc DirectiveLoc) {
3173   getStreamer().EmitCFIRememberState();
3174   return false;
3175 }
3176
3177 /// ParseDirectiveCFIRestoreState
3178 /// ::= .cfi_remember_state
3179 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3180                                                      SMLoc DirectiveLoc) {
3181   getStreamer().EmitCFIRestoreState();
3182   return false;
3183 }
3184
3185 /// ParseDirectiveCFISameValue
3186 /// ::= .cfi_same_value register
3187 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3188                                                   SMLoc DirectiveLoc) {
3189   int64_t Register = 0;
3190
3191   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3192     return true;
3193
3194   getStreamer().EmitCFISameValue(Register);
3195
3196   return false;
3197 }
3198
3199 /// ParseDirectiveCFIRestore
3200 /// ::= .cfi_restore register
3201 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3202                                                 SMLoc DirectiveLoc) {
3203   int64_t Register = 0;
3204   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3205     return true;
3206
3207   getStreamer().EmitCFIRestore(Register);
3208
3209   return false;
3210 }
3211
3212 /// ParseDirectiveCFIEscape
3213 /// ::= .cfi_escape expression[,...]
3214 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3215                                                SMLoc DirectiveLoc) {
3216   std::string Values;
3217   int64_t CurrValue;
3218   if (getParser().ParseAbsoluteExpression(CurrValue))
3219     return true;
3220
3221   Values.push_back((uint8_t)CurrValue);
3222
3223   while (getLexer().is(AsmToken::Comma)) {
3224     Lex();
3225
3226     if (getParser().ParseAbsoluteExpression(CurrValue))
3227       return true;
3228
3229     Values.push_back((uint8_t)CurrValue);
3230   }
3231
3232   getStreamer().EmitCFIEscape(Values);
3233   return false;
3234 }
3235
3236 /// ParseDirectiveCFISignalFrame
3237 /// ::= .cfi_signal_frame
3238 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3239                                                     SMLoc DirectiveLoc) {
3240   if (getLexer().isNot(AsmToken::EndOfStatement))
3241     return Error(getLexer().getLoc(),
3242                  "unexpected token in '" + Directive + "' directive");
3243
3244   getStreamer().EmitCFISignalFrame();
3245
3246   return false;
3247 }
3248
3249 /// ParseDirectiveMacrosOnOff
3250 /// ::= .macros_on
3251 /// ::= .macros_off
3252 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3253                                                  SMLoc DirectiveLoc) {
3254   if (getLexer().isNot(AsmToken::EndOfStatement))
3255     return Error(getLexer().getLoc(),
3256                  "unexpected token in '" + Directive + "' directive");
3257
3258   getParser().MacrosEnabled = Directive == ".macros_on";
3259
3260   return false;
3261 }
3262
3263 /// ParseDirectiveMacro
3264 /// ::= .macro name [parameters]
3265 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3266                                            SMLoc DirectiveLoc) {
3267   StringRef Name;
3268   if (getParser().ParseIdentifier(Name))
3269     return TokError("expected identifier in '.macro' directive");
3270
3271   MacroParameters Parameters;
3272   // Argument delimiter is initially unknown. It will be set by
3273   // ParseMacroArgument()
3274   AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3275   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3276     for (;;) {
3277       MacroParameter Parameter;
3278       if (getParser().ParseIdentifier(Parameter.first))
3279         return TokError("expected identifier in '.macro' directive");
3280
3281       if (getLexer().is(AsmToken::Equal)) {
3282         Lex();
3283         if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3284           return true;
3285       }
3286
3287       Parameters.push_back(Parameter);
3288
3289       if (getLexer().is(AsmToken::Comma))
3290         Lex();
3291       else if (getLexer().is(AsmToken::EndOfStatement))
3292         break;
3293     }
3294   }
3295
3296   // Eat the end of statement.
3297   Lex();
3298
3299   AsmToken EndToken, StartToken = getTok();
3300
3301   // Lex the macro definition.
3302   for (;;) {
3303     // Check whether we have reached the end of the file.
3304     if (getLexer().is(AsmToken::Eof))
3305       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3306
3307     // Otherwise, check whether we have reach the .endmacro.
3308     if (getLexer().is(AsmToken::Identifier) &&
3309         (getTok().getIdentifier() == ".endm" ||
3310          getTok().getIdentifier() == ".endmacro")) {
3311       EndToken = getTok();
3312       Lex();
3313       if (getLexer().isNot(AsmToken::EndOfStatement))
3314         return TokError("unexpected token in '" + EndToken.getIdentifier() +
3315                         "' directive");
3316       break;
3317     }
3318
3319     // Otherwise, scan til the end of the statement.
3320     getParser().EatToEndOfStatement();
3321   }
3322
3323   if (getParser().MacroMap.lookup(Name)) {
3324     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3325   }
3326
3327   const char *BodyStart = StartToken.getLoc().getPointer();
3328   const char *BodyEnd = EndToken.getLoc().getPointer();
3329   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3330   getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3331   return false;
3332 }
3333
3334 /// ParseDirectiveEndMacro
3335 /// ::= .endm
3336 /// ::= .endmacro
3337 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3338                                               SMLoc DirectiveLoc) {
3339   if (getLexer().isNot(AsmToken::EndOfStatement))
3340     return TokError("unexpected token in '" + Directive + "' directive");
3341
3342   // If we are inside a macro instantiation, terminate the current
3343   // instantiation.
3344   if (!getParser().ActiveMacros.empty()) {
3345     getParser().HandleMacroExit();
3346     return false;
3347   }
3348
3349   // Otherwise, this .endmacro is a stray entry in the file; well formed
3350   // .endmacro directives are handled during the macro definition parsing.
3351   return TokError("unexpected '" + Directive + "' in file, "
3352                   "no current macro definition");
3353 }
3354
3355 /// ParseDirectivePurgeMacro
3356 /// ::= .purgem
3357 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3358                                                 SMLoc DirectiveLoc) {
3359   StringRef Name;
3360   if (getParser().ParseIdentifier(Name))
3361     return TokError("expected identifier in '.purgem' directive");
3362
3363   if (getLexer().isNot(AsmToken::EndOfStatement))
3364     return TokError("unexpected token in '.purgem' directive");
3365
3366   StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3367   if (I == getParser().MacroMap.end())
3368     return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3369
3370   // Undefine the macro.
3371   delete I->getValue();
3372   getParser().MacroMap.erase(I);
3373   return false;
3374 }
3375
3376 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3377   getParser().CheckForValidSection();
3378
3379   const MCExpr *Value;
3380
3381   if (getParser().ParseExpression(Value))
3382     return true;
3383
3384   if (getLexer().isNot(AsmToken::EndOfStatement))
3385     return TokError("unexpected token in directive");
3386
3387   if (DirName[1] == 's')
3388     getStreamer().EmitSLEB128Value(Value);
3389   else
3390     getStreamer().EmitULEB128Value(Value);
3391
3392   return false;
3393 }
3394
3395 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3396   AsmToken EndToken, StartToken = getTok();
3397
3398   unsigned NestLevel = 0;
3399   for (;;) {
3400     // Check whether we have reached the end of the file.
3401     if (getLexer().is(AsmToken::Eof)) {
3402       Error(DirectiveLoc, "no matching '.endr' in definition");
3403       return 0;
3404     }
3405
3406     if (Lexer.is(AsmToken::Identifier) &&
3407         (getTok().getIdentifier() == ".rept")) {
3408       ++NestLevel;
3409     }
3410
3411     // Otherwise, check whether we have reached the .endr.
3412     if (Lexer.is(AsmToken::Identifier) &&
3413         getTok().getIdentifier() == ".endr") {
3414       if (NestLevel == 0) {
3415         EndToken = getTok();
3416         Lex();
3417         if (Lexer.isNot(AsmToken::EndOfStatement)) {
3418           TokError("unexpected token in '.endr' directive");
3419           return 0;
3420         }
3421         break;
3422       }
3423       --NestLevel;
3424     }
3425
3426     // Otherwise, scan till the end of the statement.
3427     EatToEndOfStatement();
3428   }
3429
3430   const char *BodyStart = StartToken.getLoc().getPointer();
3431   const char *BodyEnd = EndToken.getLoc().getPointer();
3432   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3433
3434   // We Are Anonymous.
3435   StringRef Name;
3436   MacroParameters Parameters;
3437   return new Macro(Name, Body, Parameters);
3438 }
3439
3440 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3441                                          raw_svector_ostream &OS) {
3442   OS << ".endr\n";
3443
3444   MemoryBuffer *Instantiation =
3445     MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3446
3447   // Create the macro instantiation object and add to the current macro
3448   // instantiation stack.
3449   MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3450                                                   getTok().getLoc(),
3451                                                   Instantiation);
3452   ActiveMacros.push_back(MI);
3453
3454   // Jump to the macro instantiation and prime the lexer.
3455   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3456   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3457   Lex();
3458 }
3459
3460 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3461   int64_t Count;
3462   if (ParseAbsoluteExpression(Count))
3463     return TokError("unexpected token in '.rept' directive");
3464
3465   if (Count < 0)
3466     return TokError("Count is negative");
3467
3468   if (Lexer.isNot(AsmToken::EndOfStatement))
3469     return TokError("unexpected token in '.rept' directive");
3470
3471   // Eat the end of statement.
3472   Lex();
3473
3474   // Lex the rept definition.
3475   Macro *M = ParseMacroLikeBody(DirectiveLoc);
3476   if (!M)
3477     return true;
3478
3479   // Macro instantiation is lexical, unfortunately. We construct a new buffer
3480   // to hold the macro body with substitutions.
3481   SmallString<256> Buf;
3482   MacroParameters Parameters;
3483   MacroArguments A;
3484   raw_svector_ostream OS(Buf);
3485   while (Count--) {
3486     if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3487       return true;
3488   }
3489   InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3490
3491   return false;
3492 }
3493
3494 /// ParseDirectiveIrp
3495 /// ::= .irp symbol,values
3496 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3497   MacroParameters Parameters;
3498   MacroParameter Parameter;
3499
3500   if (ParseIdentifier(Parameter.first))
3501     return TokError("expected identifier in '.irp' directive");
3502
3503   Parameters.push_back(Parameter);
3504
3505   if (Lexer.isNot(AsmToken::Comma))
3506     return TokError("expected comma in '.irp' directive");
3507
3508   Lex();
3509
3510   MacroArguments A;
3511   if (ParseMacroArguments(0, A))
3512     return true;
3513
3514   // Eat the end of statement.
3515   Lex();
3516
3517   // Lex the irp definition.
3518   Macro *M = ParseMacroLikeBody(DirectiveLoc);
3519   if (!M)
3520     return true;
3521
3522   // Macro instantiation is lexical, unfortunately. We construct a new buffer
3523   // to hold the macro body with substitutions.
3524   SmallString<256> Buf;
3525   raw_svector_ostream OS(Buf);
3526
3527   for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3528     MacroArguments Args;
3529     Args.push_back(*i);
3530
3531     if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3532       return true;
3533   }
3534
3535   InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3536
3537   return false;
3538 }
3539
3540 /// ParseDirectiveIrpc
3541 /// ::= .irpc symbol,values
3542 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3543   MacroParameters Parameters;
3544   MacroParameter Parameter;
3545
3546   if (ParseIdentifier(Parameter.first))
3547     return TokError("expected identifier in '.irpc' directive");
3548
3549   Parameters.push_back(Parameter);
3550
3551   if (Lexer.isNot(AsmToken::Comma))
3552     return TokError("expected comma in '.irpc' directive");
3553
3554   Lex();
3555
3556   MacroArguments A;
3557   if (ParseMacroArguments(0, A))
3558     return true;
3559
3560   if (A.size() != 1 || A.front().size() != 1)
3561     return TokError("unexpected token in '.irpc' directive");
3562
3563   // Eat the end of statement.
3564   Lex();
3565
3566   // Lex the irpc definition.
3567   Macro *M = ParseMacroLikeBody(DirectiveLoc);
3568   if (!M)
3569     return true;
3570
3571   // Macro instantiation is lexical, unfortunately. We construct a new buffer
3572   // to hold the macro body with substitutions.
3573   SmallString<256> Buf;
3574   raw_svector_ostream OS(Buf);
3575
3576   StringRef Values = A.front().front().getString();
3577   std::size_t I, End = Values.size();
3578   for (I = 0; I < End; ++I) {
3579     MacroArgument Arg;
3580     Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3581
3582     MacroArguments Args;
3583     Args.push_back(Arg);
3584
3585     if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3586       return true;
3587   }
3588
3589   InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3590
3591   return false;
3592 }
3593
3594 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3595   if (ActiveMacros.empty())
3596     return TokError("unmatched '.endr' directive");
3597
3598   // The only .repl that should get here are the ones created by
3599   // InstantiateMacroLikeBody.
3600   assert(getLexer().is(AsmToken::EndOfStatement));
3601
3602   HandleMacroExit();
3603   return false;
3604 }
3605
3606 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3607   const MCExpr *Value;
3608   SMLoc ExprLoc = getLexer().getLoc();
3609   if (ParseExpression(Value))
3610     return true;
3611   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3612   if (!MCE)
3613     return Error(ExprLoc, "unexpected expression in _emit");
3614   uint64_t IntValue = MCE->getValue();
3615   if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3616     return Error(ExprLoc, "literal value out of range for directive");
3617
3618   Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3619   return false;
3620 }
3621
3622 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3623                                  unsigned &NumOutputs, unsigned &NumInputs,
3624                                  SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3625                                  SmallVectorImpl<std::string> &Constraints,
3626                                  SmallVectorImpl<std::string> &Clobbers,
3627                                  const MCInstrInfo *MII,
3628                                  const MCInstPrinter *IP,
3629                                  MCAsmParserSemaCallback &SI) {
3630   SmallVector<void *, 4> InputDecls;
3631   SmallVector<void *, 4> OutputDecls;
3632   SmallVector<bool, 4> InputDeclsOffsetOf;
3633   SmallVector<bool, 4> OutputDeclsOffsetOf;
3634   SmallVector<std::string, 4> InputConstraints;
3635   SmallVector<std::string, 4> OutputConstraints;
3636   std::set<std::string> ClobberRegs;
3637
3638   SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3639
3640   // Prime the lexer.
3641   Lex();
3642
3643   // While we have input, parse each statement.
3644   unsigned InputIdx = 0;
3645   unsigned OutputIdx = 0;
3646   while (getLexer().isNot(AsmToken::Eof)) {
3647     ParseStatementInfo Info(&AsmStrRewrites);
3648     if (ParseStatement(Info))
3649       return true;
3650
3651     if (Info.Opcode != ~0U) {
3652       const MCInstrDesc &Desc = MII->get(Info.Opcode);
3653
3654       // Build the list of clobbers, outputs and inputs.
3655       for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3656         MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3657
3658         // Immediate.
3659         if (Operand->isImm()) {
3660           if (Operand->needAsmRewrite())
3661             AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3662                                                 Operand->getStartLoc()));
3663           continue;
3664         }
3665
3666         // Register operand.
3667         if (Operand->isReg() && !Operand->isOffsetOf()) {
3668           unsigned NumDefs = Desc.getNumDefs();
3669           // Clobber.
3670           if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3671             std::string Reg;
3672             raw_string_ostream OS(Reg);
3673             IP->printRegName(OS, Operand->getReg());
3674             ClobberRegs.insert(StringRef(OS.str()));
3675           }
3676           continue;
3677         }
3678
3679         // Expr/Input or Output.
3680         unsigned Size;
3681         void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3682                                                     Size);
3683         if (OpDecl) {
3684           bool isOutput = (i == 1) && Desc.mayStore();
3685           if (!Operand->isOffsetOf() && Operand->needSizeDirective())
3686             AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3687                                                 Operand->getStartLoc(),
3688                                                 /*Len*/0,
3689                                                 Operand->getMemSize()));
3690           if (isOutput) {
3691             std::string Constraint = "=";
3692             ++InputIdx;
3693             OutputDecls.push_back(OpDecl);
3694             OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3695             Constraint += Operand->getConstraint().str();
3696             OutputConstraints.push_back(Constraint);
3697             AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3698                                                 Operand->getStartLoc(),
3699                                                 Operand->getNameLen()));
3700           } else {
3701             InputDecls.push_back(OpDecl);
3702             InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3703             InputConstraints.push_back(Operand->getConstraint().str());
3704             AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3705                                                 Operand->getStartLoc(),
3706                                                 Operand->getNameLen()));
3707           }
3708         }
3709       }
3710     }
3711   }
3712
3713   // Set the number of Outputs and Inputs.
3714   NumOutputs = OutputDecls.size();
3715   NumInputs = InputDecls.size();
3716
3717   // Set the unique clobbers.
3718   for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3719          E = ClobberRegs.end(); I != E; ++I)
3720     Clobbers.push_back(*I);
3721
3722   // Merge the various outputs and inputs.  Output are expected first.
3723   if (NumOutputs || NumInputs) {
3724     unsigned NumExprs = NumOutputs + NumInputs;
3725     OpDecls.resize(NumExprs);
3726     Constraints.resize(NumExprs);
3727     // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3728     // constraint for offsetof.  This needs to be cleaned up!
3729     for (unsigned i = 0; i < NumOutputs; ++i) {
3730       OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3731       Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
3732     }
3733     for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3734       OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3735       Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
3736     }
3737   }
3738
3739   // Build the IR assembly string.
3740   std::string AsmStringIR;
3741   AsmRewriteKind PrevKind = AOK_Imm;
3742   raw_string_ostream OS(AsmStringIR);
3743   const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3744   for (SmallVectorImpl<struct AsmRewrite>::iterator
3745          I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3746     const char *Loc = (*I).Loc.getPointer();
3747
3748     AsmRewriteKind Kind = (*I).Kind;
3749
3750     // Emit everything up to the immediate/expression.  If the previous rewrite
3751     // was a size directive, then this has already been done.
3752     if (PrevKind != AOK_SizeDirective)
3753       OS << StringRef(Start, Loc - Start);
3754     PrevKind = Kind;
3755
3756     // Skip the original expression.
3757     if (Kind == AOK_Skip) {
3758       Start = Loc + (*I).Len;
3759       continue;
3760     }
3761
3762     // Rewrite expressions in $N notation.
3763     switch (Kind) {
3764     default: break;
3765     case AOK_Imm:
3766       OS << Twine("$$");
3767       OS << (*I).Val;
3768       break;
3769     case AOK_ImmPrefix:
3770       OS << Twine("$$");
3771       break;
3772     case AOK_Input:
3773       OS << '$';
3774       OS << InputIdx++;
3775       break;
3776     case AOK_Output:
3777       OS << '$';
3778       OS << OutputIdx++;
3779       break;
3780     case AOK_SizeDirective:
3781       switch((*I).Val) {
3782       default: break;
3783       case 8:  OS << "byte ptr "; break;
3784       case 16: OS << "word ptr "; break;
3785       case 32: OS << "dword ptr "; break;
3786       case 64: OS << "qword ptr "; break;
3787       case 80: OS << "xword ptr "; break;
3788       case 128: OS << "xmmword ptr "; break;
3789       case 256: OS << "ymmword ptr "; break;
3790       }
3791       break;
3792     case AOK_Emit:
3793       OS << ".byte";
3794       break;
3795     case AOK_DotOperator:
3796       OS << (*I).Val;
3797       break;
3798     }
3799
3800     // Skip the original expression.
3801     if (Kind != AOK_SizeDirective)
3802       Start = Loc + (*I).Len;
3803   }
3804
3805   // Emit the remainder of the asm string.
3806   const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3807   if (Start != AsmEnd)
3808     OS << StringRef(Start, AsmEnd - Start);
3809
3810   AsmString = OS.str();
3811   return false;
3812 }
3813
3814 /// \brief Create an MCAsmParser instance.
3815 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3816                                      MCContext &C, MCStreamer &Out,
3817                                      const MCAsmInfo &MAI) {
3818   return new AsmParser(SM, C, Out, MAI);
3819 }