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