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