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