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