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