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