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