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