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