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