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