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