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