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