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