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