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