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