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