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