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