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