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