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