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