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