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