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