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