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