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