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