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