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