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