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