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