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