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