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