Add support for specifying register name in cfi-register/offset/def
[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/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetAsmParser.h"
35 #include <cctype>
36 #include <vector>
37 using namespace llvm;
38
39 namespace {
40
41 /// \brief Helper class for tracking macro definitions.
42 struct Macro {
43   StringRef Name;
44   StringRef Body;
45
46 public:
47   Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48 };
49
50 /// \brief Helper class for storing information about an active macro
51 /// instantiation.
52 struct MacroInstantiation {
53   /// The macro being instantiated.
54   const Macro *TheMacro;
55
56   /// The macro instantiation with substitutions.
57   MemoryBuffer *Instantiation;
58
59   /// The location of the instantiation.
60   SMLoc InstantiationLoc;
61
62   /// The location where parsing should resume upon instantiation completion.
63   SMLoc ExitLoc;
64
65 public:
66   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67                      const std::vector<std::vector<AsmToken> > &A);
68 };
69
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72   friend class GenericAsmParser;
73
74   AsmParser(const AsmParser &);   // DO NOT IMPLEMENT
75   void operator=(const AsmParser &);  // DO NOT IMPLEMENT
76 private:
77   AsmLexer Lexer;
78   MCContext &Ctx;
79   MCStreamer &Out;
80   SourceMgr &SrcMgr;
81   MCAsmParserExtension *GenericParser;
82   MCAsmParserExtension *PlatformParser;
83
84   /// This is the current buffer index we're lexing from as managed by the
85   /// SourceMgr object.
86   int CurBuffer;
87
88   AsmCond TheCondState;
89   std::vector<AsmCond> TheCondStack;
90
91   /// DirectiveMap - This is a table handlers for directives.  Each handler is
92   /// invoked after the directive identifier is read and is responsible for
93   /// parsing and validating the rest of the directive.  The handler is passed
94   /// in the directive name and the location of the directive keyword.
95   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
96
97   /// MacroMap - Map of currently defined macros.
98   StringMap<Macro*> MacroMap;
99
100   /// ActiveMacros - Stack of active macro instantiations.
101   std::vector<MacroInstantiation*> ActiveMacros;
102
103   /// Boolean tracking whether macro substitution is enabled.
104   unsigned MacrosEnabled : 1;
105
106   /// Flag tracking whether any errors have been encountered.
107   unsigned HadError : 1;
108
109 public:
110   AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111             const MCAsmInfo &MAI);
112   ~AsmParser();
113
114   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115
116   void AddDirectiveHandler(MCAsmParserExtension *Object,
117                            StringRef Directive,
118                            DirectiveHandler Handler) {
119     DirectiveMap[Directive] = std::make_pair(Object, Handler);
120   }
121
122 public:
123   /// @name MCAsmParser Interface
124   /// {
125
126   virtual SourceMgr &getSourceManager() { return SrcMgr; }
127   virtual MCAsmLexer &getLexer() { return Lexer; }
128   virtual MCContext &getContext() { return Ctx; }
129   virtual MCStreamer &getStreamer() { return Out; }
130
131   virtual void Warning(SMLoc L, const Twine &Meg);
132   virtual bool Error(SMLoc L, const Twine &Msg);
133
134   const AsmToken &Lex();
135
136   bool ParseExpression(const MCExpr *&Res);
137   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139   virtual bool ParseAbsoluteExpression(int64_t &Res);
140
141   /// }
142
143 private:
144   void CheckForValidSection();
145
146   bool ParseStatement();
147
148   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149   void HandleMacroExit();
150
151   void PrintMacroInstantiations();
152   void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
153     SrcMgr.PrintMessage(Loc, Msg, Type);
154   }
155
156   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
157   bool EnterIncludeFile(const std::string &Filename);
158
159   /// \brief Reset the current lexer position to that given by \arg Loc. The
160   /// current token is not set; clients should ensure Lex() is called
161   /// subsequently.
162   void JumpToLoc(SMLoc Loc);
163
164   void EatToEndOfStatement();
165
166   /// \brief Parse up to the end of statement and a return the contents from the
167   /// current token until the end of the statement; the current token on exit
168   /// will be either the EndOfStatement or EOF.
169   StringRef ParseStringToEndOfStatement();
170
171   bool ParseAssignment(StringRef Name);
172
173   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
174   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
175   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
176
177   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
178   /// and set \arg Res to the identifier contents.
179   bool ParseIdentifier(StringRef &Res);
180
181   // Directive Parsing.
182
183  // ".ascii", ".asciiz", ".string"
184   bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
185   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
186   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
187   bool ParseDirectiveFill(); // ".fill"
188   bool ParseDirectiveSpace(); // ".space"
189   bool ParseDirectiveZero(); // ".zero"
190   bool ParseDirectiveSet(StringRef IDVal); // ".set" or ".equ"
191   bool ParseDirectiveOrg(); // ".org"
192   // ".align{,32}", ".p2align{,w,l}"
193   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
194
195   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
196   /// accepts a single symbol (which should be a label or an external).
197   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
198
199   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
200
201   bool ParseDirectiveAbort(); // ".abort"
202   bool ParseDirectiveInclude(); // ".include"
203
204   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
205   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
206   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
207   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
208
209   /// ParseEscapedString - Parse the current token as a string which may include
210   /// escaped characters and return the string contents.
211   bool ParseEscapedString(std::string &Data);
212
213   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
214                                     MCSymbolRefExpr::VariantKind Variant);
215 };
216
217 /// \brief Generic implementations of directive handling, etc. which is shared
218 /// (or the default, at least) for all assembler parser.
219 class GenericAsmParser : public MCAsmParserExtension {
220   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
221   void AddDirectiveHandler(StringRef Directive) {
222     getParser().AddDirectiveHandler(this, Directive,
223                                     HandleDirective<GenericAsmParser, Handler>);
224   }
225
226 public:
227   GenericAsmParser() {}
228
229   AsmParser &getParser() {
230     return (AsmParser&) this->MCAsmParserExtension::getParser();
231   }
232
233   virtual void Initialize(MCAsmParser &Parser) {
234     // Call the base implementation.
235     this->MCAsmParserExtension::Initialize(Parser);
236
237     // Debugging directives.
238     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
239     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
240     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
241     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
242
243     // CFI directives.
244     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
245                                                               ".cfi_startproc");
246     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
247                                                                 ".cfi_endproc");
248     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
249                                                          ".cfi_def_cfa");
250     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
251                                                          ".cfi_def_cfa_offset");
252     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
253                                                        ".cfi_def_cfa_register");
254     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
255                                                                  ".cfi_offset");
256     AddDirectiveHandler<
257      &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
258     AddDirectiveHandler<
259             &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
260     AddDirectiveHandler<
261       &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
262     AddDirectiveHandler<
263       &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
264
265     // Macro directives.
266     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
267       ".macros_on");
268     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
269       ".macros_off");
270     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
271     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
272     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
273
274     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
275     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
276   }
277
278   bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
279
280   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
281   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
282   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
283   bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
284   bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
285   bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
286   bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
287   bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
288   bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
289   bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
290   bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
291   bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
292   bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
293
294   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
295   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
296   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
297
298   bool ParseDirectiveLEB128(StringRef, SMLoc);
299 };
300
301 }
302
303 namespace llvm {
304
305 extern MCAsmParserExtension *createDarwinAsmParser();
306 extern MCAsmParserExtension *createELFAsmParser();
307 extern MCAsmParserExtension *createCOFFAsmParser();
308
309 }
310
311 enum { DEFAULT_ADDRSPACE = 0 };
312
313 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
314                      MCStreamer &_Out, const MCAsmInfo &_MAI)
315   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
316     GenericParser(new GenericAsmParser), PlatformParser(0),
317     CurBuffer(0), MacrosEnabled(true) {
318   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
319
320   // Initialize the generic parser.
321   GenericParser->Initialize(*this);
322
323   // Initialize the platform / file format parser.
324   //
325   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
326   // created.
327   if (_MAI.hasMicrosoftFastStdCallMangling()) {
328     PlatformParser = createCOFFAsmParser();
329     PlatformParser->Initialize(*this);
330   } else if (_MAI.hasSubsectionsViaSymbols()) {
331     PlatformParser = createDarwinAsmParser();
332     PlatformParser->Initialize(*this);
333   } else {
334     PlatformParser = createELFAsmParser();
335     PlatformParser->Initialize(*this);
336   }
337 }
338
339 AsmParser::~AsmParser() {
340   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
341
342   // Destroy any macros.
343   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
344          ie = MacroMap.end(); it != ie; ++it)
345     delete it->getValue();
346
347   delete PlatformParser;
348   delete GenericParser;
349 }
350
351 void AsmParser::PrintMacroInstantiations() {
352   // Print the active macro instantiation stack.
353   for (std::vector<MacroInstantiation*>::const_reverse_iterator
354          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
355     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
356                  "note");
357 }
358
359 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
360   PrintMessage(L, Msg, "warning");
361   PrintMacroInstantiations();
362 }
363
364 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
365   HadError = true;
366   PrintMessage(L, Msg, "error");
367   PrintMacroInstantiations();
368   return true;
369 }
370
371 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
372   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
373   if (NewBuf == -1)
374     return true;
375
376   CurBuffer = NewBuf;
377
378   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
379
380   return false;
381 }
382
383 void AsmParser::JumpToLoc(SMLoc Loc) {
384   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
385   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
386 }
387
388 const AsmToken &AsmParser::Lex() {
389   const AsmToken *tok = &Lexer.Lex();
390
391   if (tok->is(AsmToken::Eof)) {
392     // If this is the end of an included file, pop the parent file off the
393     // include stack.
394     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
395     if (ParentIncludeLoc != SMLoc()) {
396       JumpToLoc(ParentIncludeLoc);
397       tok = &Lexer.Lex();
398     }
399   }
400
401   if (tok->is(AsmToken::Error))
402     Error(Lexer.getErrLoc(), Lexer.getErr());
403
404   return *tok;
405 }
406
407 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
408   // Create the initial section, if requested.
409   if (!NoInitialTextSection)
410     Out.InitSections();
411
412   // Prime the lexer.
413   Lex();
414
415   HadError = false;
416   AsmCond StartingCondState = TheCondState;
417
418   // While we have input, parse each statement.
419   while (Lexer.isNot(AsmToken::Eof)) {
420     if (!ParseStatement()) continue;
421
422     // We had an error, validate that one was emitted and recover by skipping to
423     // the next line.
424     assert(HadError && "Parse statement returned an error, but none emitted!");
425     EatToEndOfStatement();
426   }
427
428   if (TheCondState.TheCond != StartingCondState.TheCond ||
429       TheCondState.Ignore != StartingCondState.Ignore)
430     return TokError("unmatched .ifs or .elses");
431
432   // Check to see there are no empty DwarfFile slots.
433   const std::vector<MCDwarfFile *> &MCDwarfFiles =
434     getContext().getMCDwarfFiles();
435   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
436     if (!MCDwarfFiles[i])
437       TokError("unassigned file number: " + Twine(i) + " for .file directives");
438   }
439
440   // Finalize the output stream if there are no errors and if the client wants
441   // us to.
442   if (!HadError && !NoFinalize)
443     Out.Finish();
444
445   return HadError;
446 }
447
448 void AsmParser::CheckForValidSection() {
449   if (!getStreamer().getCurrentSection()) {
450     TokError("expected section directive before assembly directive");
451     Out.SwitchSection(Ctx.getMachOSection(
452                         "__TEXT", "__text",
453                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
454                         0, SectionKind::getText()));
455   }
456 }
457
458 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
459 void AsmParser::EatToEndOfStatement() {
460   while (Lexer.isNot(AsmToken::EndOfStatement) &&
461          Lexer.isNot(AsmToken::Eof))
462     Lex();
463
464   // Eat EOL.
465   if (Lexer.is(AsmToken::EndOfStatement))
466     Lex();
467 }
468
469 StringRef AsmParser::ParseStringToEndOfStatement() {
470   const char *Start = getTok().getLoc().getPointer();
471
472   while (Lexer.isNot(AsmToken::EndOfStatement) &&
473          Lexer.isNot(AsmToken::Eof))
474     Lex();
475
476   const char *End = getTok().getLoc().getPointer();
477   return StringRef(Start, End - Start);
478 }
479
480 /// ParseParenExpr - Parse a paren expression and return it.
481 /// NOTE: This assumes the leading '(' has already been consumed.
482 ///
483 /// parenexpr ::= expr)
484 ///
485 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
486   if (ParseExpression(Res)) return true;
487   if (Lexer.isNot(AsmToken::RParen))
488     return TokError("expected ')' in parentheses expression");
489   EndLoc = Lexer.getLoc();
490   Lex();
491   return false;
492 }
493
494 /// ParsePrimaryExpr - Parse a primary expression and return it.
495 ///  primaryexpr ::= (parenexpr
496 ///  primaryexpr ::= symbol
497 ///  primaryexpr ::= number
498 ///  primaryexpr ::= '.'
499 ///  primaryexpr ::= ~,+,- primaryexpr
500 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
501   switch (Lexer.getKind()) {
502   default:
503     return TokError("unknown token in expression");
504   case AsmToken::Exclaim:
505     Lex(); // Eat the operator.
506     if (ParsePrimaryExpr(Res, EndLoc))
507       return true;
508     Res = MCUnaryExpr::CreateLNot(Res, getContext());
509     return false;
510   case AsmToken::Dollar:
511   case AsmToken::String:
512   case AsmToken::Identifier: {
513     EndLoc = Lexer.getLoc();
514
515     StringRef Identifier;
516     if (ParseIdentifier(Identifier))
517       return false;
518
519     // This is a symbol reference.
520     std::pair<StringRef, StringRef> Split = Identifier.split('@');
521     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
522
523     // Lookup the symbol variant if used.
524     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
525     if (Split.first.size() != Identifier.size()) {
526       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
527       if (Variant == MCSymbolRefExpr::VK_Invalid) {
528         Variant = MCSymbolRefExpr::VK_None;
529         return TokError("invalid variant '" + Split.second + "'");
530       }
531     }
532
533     // If this is an absolute variable reference, substitute it now to preserve
534     // semantics in the face of reassignment.
535     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
536       if (Variant)
537         return Error(EndLoc, "unexpected modifier on variable reference");
538
539       Res = Sym->getVariableValue();
540       return false;
541     }
542
543     // Otherwise create a symbol ref.
544     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
545     return false;
546   }
547   case AsmToken::Integer: {
548     SMLoc Loc = getTok().getLoc();
549     int64_t IntVal = getTok().getIntVal();
550     Res = MCConstantExpr::Create(IntVal, getContext());
551     EndLoc = Lexer.getLoc();
552     Lex(); // Eat token.
553     // Look for 'b' or 'f' following an Integer as a directional label
554     if (Lexer.getKind() == AsmToken::Identifier) {
555       StringRef IDVal = getTok().getString();
556       if (IDVal == "f" || IDVal == "b"){
557         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
558                                                       IDVal == "f" ? 1 : 0);
559         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
560                                       getContext());
561         if(IDVal == "b" && Sym->isUndefined())
562           return Error(Loc, "invalid reference to undefined symbol");
563         EndLoc = Lexer.getLoc();
564         Lex(); // Eat identifier.
565       }
566     }
567     return false;
568   }
569   case AsmToken::Real: {
570     APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
571     int64_t IntVal = RealVal.bitcastToAPInt().getSExtValue();
572     Res = MCConstantExpr::Create(IntVal, getContext());
573     Lex(); // Eat token.
574     return false;
575   }
576   case AsmToken::Dot: {
577     // This is a '.' reference, which references the current PC.  Emit a
578     // temporary label to the streamer and refer to it.
579     MCSymbol *Sym = Ctx.CreateTempSymbol();
580     Out.EmitLabel(Sym);
581     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
582     EndLoc = Lexer.getLoc();
583     Lex(); // Eat identifier.
584     return false;
585   }
586   case AsmToken::LParen:
587     Lex(); // Eat the '('.
588     return ParseParenExpr(Res, EndLoc);
589   case AsmToken::Minus:
590     Lex(); // Eat the operator.
591     if (ParsePrimaryExpr(Res, EndLoc))
592       return true;
593     Res = MCUnaryExpr::CreateMinus(Res, getContext());
594     return false;
595   case AsmToken::Plus:
596     Lex(); // Eat the operator.
597     if (ParsePrimaryExpr(Res, EndLoc))
598       return true;
599     Res = MCUnaryExpr::CreatePlus(Res, getContext());
600     return false;
601   case AsmToken::Tilde:
602     Lex(); // Eat the operator.
603     if (ParsePrimaryExpr(Res, EndLoc))
604       return true;
605     Res = MCUnaryExpr::CreateNot(Res, getContext());
606     return false;
607   }
608 }
609
610 bool AsmParser::ParseExpression(const MCExpr *&Res) {
611   SMLoc EndLoc;
612   return ParseExpression(Res, EndLoc);
613 }
614
615 const MCExpr *
616 AsmParser::ApplyModifierToExpr(const MCExpr *E,
617                                MCSymbolRefExpr::VariantKind Variant) {
618   // Recurse over the given expression, rebuilding it to apply the given variant
619   // if there is exactly one symbol.
620   switch (E->getKind()) {
621   case MCExpr::Target:
622   case MCExpr::Constant:
623     return 0;
624
625   case MCExpr::SymbolRef: {
626     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
627
628     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
629       TokError("invalid variant on expression '" +
630                getTok().getIdentifier() + "' (already modified)");
631       return E;
632     }
633
634     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
635   }
636
637   case MCExpr::Unary: {
638     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
639     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
640     if (!Sub)
641       return 0;
642     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
643   }
644
645   case MCExpr::Binary: {
646     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
647     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
648     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
649
650     if (!LHS && !RHS)
651       return 0;
652
653     if (!LHS) LHS = BE->getLHS();
654     if (!RHS) RHS = BE->getRHS();
655
656     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
657   }
658   }
659
660   assert(0 && "Invalid expression kind!");
661   return 0;
662 }
663
664 /// ParseExpression - Parse an expression and return it.
665 ///
666 ///  expr ::= expr +,- expr          -> lowest.
667 ///  expr ::= expr |,^,&,! expr      -> middle.
668 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
669 ///  expr ::= primaryexpr
670 ///
671 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
672   // Parse the expression.
673   Res = 0;
674   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
675     return true;
676
677   // As a special case, we support 'a op b @ modifier' by rewriting the
678   // expression to include the modifier. This is inefficient, but in general we
679   // expect users to use 'a@modifier op b'.
680   if (Lexer.getKind() == AsmToken::At) {
681     Lex();
682
683     if (Lexer.isNot(AsmToken::Identifier))
684       return TokError("unexpected symbol modifier following '@'");
685
686     MCSymbolRefExpr::VariantKind Variant =
687       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
688     if (Variant == MCSymbolRefExpr::VK_Invalid)
689       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
690
691     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
692     if (!ModifiedRes) {
693       return TokError("invalid modifier '" + getTok().getIdentifier() +
694                       "' (no symbols present)");
695       return true;
696     }
697
698     Res = ModifiedRes;
699     Lex();
700   }
701
702   // Try to constant fold it up front, if possible.
703   int64_t Value;
704   if (Res->EvaluateAsAbsolute(Value))
705     Res = MCConstantExpr::Create(Value, getContext());
706
707   return false;
708 }
709
710 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
711   Res = 0;
712   return ParseParenExpr(Res, EndLoc) ||
713          ParseBinOpRHS(1, Res, EndLoc);
714 }
715
716 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
717   const MCExpr *Expr;
718
719   SMLoc StartLoc = Lexer.getLoc();
720   if (ParseExpression(Expr))
721     return true;
722
723   if (!Expr->EvaluateAsAbsolute(Res))
724     return Error(StartLoc, "expected absolute expression");
725
726   return false;
727 }
728
729 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
730                                    MCBinaryExpr::Opcode &Kind) {
731   switch (K) {
732   default:
733     return 0;    // not a binop.
734
735     // Lowest Precedence: &&, ||, @
736   case AsmToken::AmpAmp:
737     Kind = MCBinaryExpr::LAnd;
738     return 1;
739   case AsmToken::PipePipe:
740     Kind = MCBinaryExpr::LOr;
741     return 1;
742
743
744     // Low Precedence: |, &, ^
745     //
746     // FIXME: gas seems to support '!' as an infix operator?
747   case AsmToken::Pipe:
748     Kind = MCBinaryExpr::Or;
749     return 2;
750   case AsmToken::Caret:
751     Kind = MCBinaryExpr::Xor;
752     return 2;
753   case AsmToken::Amp:
754     Kind = MCBinaryExpr::And;
755     return 2;
756
757     // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
758   case AsmToken::EqualEqual:
759     Kind = MCBinaryExpr::EQ;
760     return 3;
761   case AsmToken::ExclaimEqual:
762   case AsmToken::LessGreater:
763     Kind = MCBinaryExpr::NE;
764     return 3;
765   case AsmToken::Less:
766     Kind = MCBinaryExpr::LT;
767     return 3;
768   case AsmToken::LessEqual:
769     Kind = MCBinaryExpr::LTE;
770     return 3;
771   case AsmToken::Greater:
772     Kind = MCBinaryExpr::GT;
773     return 3;
774   case AsmToken::GreaterEqual:
775     Kind = MCBinaryExpr::GTE;
776     return 3;
777
778     // High Intermediate Precedence: +, -
779   case AsmToken::Plus:
780     Kind = MCBinaryExpr::Add;
781     return 4;
782   case AsmToken::Minus:
783     Kind = MCBinaryExpr::Sub;
784     return 4;
785
786     // Highest Precedence: *, /, %, <<, >>
787   case AsmToken::Star:
788     Kind = MCBinaryExpr::Mul;
789     return 5;
790   case AsmToken::Slash:
791     Kind = MCBinaryExpr::Div;
792     return 5;
793   case AsmToken::Percent:
794     Kind = MCBinaryExpr::Mod;
795     return 5;
796   case AsmToken::LessLess:
797     Kind = MCBinaryExpr::Shl;
798     return 5;
799   case AsmToken::GreaterGreater:
800     Kind = MCBinaryExpr::Shr;
801     return 5;
802   }
803 }
804
805
806 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
807 /// Res contains the LHS of the expression on input.
808 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
809                               SMLoc &EndLoc) {
810   while (1) {
811     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
812     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
813
814     // If the next token is lower precedence than we are allowed to eat, return
815     // successfully with what we ate already.
816     if (TokPrec < Precedence)
817       return false;
818
819     Lex();
820
821     // Eat the next primary expression.
822     const MCExpr *RHS;
823     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
824
825     // If BinOp binds less tightly with RHS than the operator after RHS, let
826     // the pending operator take RHS as its LHS.
827     MCBinaryExpr::Opcode Dummy;
828     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
829     if (TokPrec < NextTokPrec) {
830       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
831     }
832
833     // Merge LHS and RHS according to operator.
834     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
835   }
836 }
837
838
839
840
841 /// ParseStatement:
842 ///   ::= EndOfStatement
843 ///   ::= Label* Directive ...Operands... EndOfStatement
844 ///   ::= Label* Identifier OperandList* EndOfStatement
845 bool AsmParser::ParseStatement() {
846   if (Lexer.is(AsmToken::EndOfStatement)) {
847     Out.AddBlankLine();
848     Lex();
849     return false;
850   }
851
852   // Statements always start with an identifier or are a full line comment.
853   AsmToken ID = getTok();
854   SMLoc IDLoc = ID.getLoc();
855   StringRef IDVal;
856   int64_t LocalLabelVal = -1;
857   // A full line comment is a '#' as the first token.
858   if (Lexer.is(AsmToken::Hash)) {
859     EatToEndOfStatement();
860     return false;
861   }
862   // Allow an integer followed by a ':' as a directional local label.
863   if (Lexer.is(AsmToken::Integer)) {
864     LocalLabelVal = getTok().getIntVal();
865     if (LocalLabelVal < 0) {
866       if (!TheCondState.Ignore)
867         return TokError("unexpected token at start of statement");
868       IDVal = "";
869     }
870     else {
871       IDVal = getTok().getString();
872       Lex(); // Consume the integer token to be used as an identifier token.
873       if (Lexer.getKind() != AsmToken::Colon) {
874         if (!TheCondState.Ignore)
875           return TokError("unexpected token at start of statement");
876       }
877     }
878   }
879   else if (ParseIdentifier(IDVal)) {
880     if (!TheCondState.Ignore)
881       return TokError("unexpected token at start of statement");
882     IDVal = "";
883   }
884
885   // Handle conditional assembly here before checking for skipping.  We
886   // have to do this so that .endif isn't skipped in a ".if 0" block for
887   // example.
888   if (IDVal == ".if")
889     return ParseDirectiveIf(IDLoc);
890   if (IDVal == ".elseif")
891     return ParseDirectiveElseIf(IDLoc);
892   if (IDVal == ".else")
893     return ParseDirectiveElse(IDLoc);
894   if (IDVal == ".endif")
895     return ParseDirectiveEndIf(IDLoc);
896
897   // If we are in a ".if 0" block, ignore this statement.
898   if (TheCondState.Ignore) {
899     EatToEndOfStatement();
900     return false;
901   }
902
903   // FIXME: Recurse on local labels?
904
905   // See what kind of statement we have.
906   switch (Lexer.getKind()) {
907   case AsmToken::Colon: {
908     CheckForValidSection();
909
910     // identifier ':'   -> Label.
911     Lex();
912
913     // Diagnose attempt to use a variable as a label.
914     //
915     // FIXME: Diagnostics. Note the location of the definition as a label.
916     // FIXME: This doesn't diagnose assignment to a symbol which has been
917     // implicitly marked as external.
918     MCSymbol *Sym;
919     if (LocalLabelVal == -1)
920       Sym = getContext().GetOrCreateSymbol(IDVal);
921     else
922       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
923     if (!Sym->isUndefined() || Sym->isVariable())
924       return Error(IDLoc, "invalid symbol redefinition");
925
926     // Emit the label.
927     Out.EmitLabel(Sym);
928
929     // Consume any end of statement token, if present, to avoid spurious
930     // AddBlankLine calls().
931     if (Lexer.is(AsmToken::EndOfStatement)) {
932       Lex();
933       if (Lexer.is(AsmToken::Eof))
934         return false;
935     }
936
937     return ParseStatement();
938   }
939
940   case AsmToken::Equal:
941     // identifier '=' ... -> assignment statement
942     Lex();
943
944     return ParseAssignment(IDVal);
945
946   default: // Normal instruction or directive.
947     break;
948   }
949
950   // If macros are enabled, check to see if this is a macro instantiation.
951   if (MacrosEnabled)
952     if (const Macro *M = MacroMap.lookup(IDVal))
953       return HandleMacroEntry(IDVal, IDLoc, M);
954
955   // Otherwise, we have a normal instruction or directive.
956   if (IDVal[0] == '.') {
957     // Assembler features
958     if (IDVal == ".set" || IDVal == ".equ")
959       return ParseDirectiveSet(IDVal);
960
961     // Data directives
962
963     if (IDVal == ".ascii")
964       return ParseDirectiveAscii(IDVal, false);
965     if (IDVal == ".asciz" || IDVal == ".string")
966       return ParseDirectiveAscii(IDVal, true);
967
968     if (IDVal == ".byte")
969       return ParseDirectiveValue(1);
970     if (IDVal == ".short")
971       return ParseDirectiveValue(2);
972     if (IDVal == ".value")
973       return ParseDirectiveValue(2);
974     if (IDVal == ".2byte")
975       return ParseDirectiveValue(2);
976     if (IDVal == ".long")
977       return ParseDirectiveValue(4);
978     if (IDVal == ".int")
979       return ParseDirectiveValue(4);
980     if (IDVal == ".4byte")
981       return ParseDirectiveValue(4);
982     if (IDVal == ".quad")
983       return ParseDirectiveValue(8);
984     if (IDVal == ".8byte")
985       return ParseDirectiveValue(8);
986     if (IDVal == ".single")
987       return ParseDirectiveRealValue(APFloat::IEEEsingle);
988     if (IDVal == ".double")
989       return ParseDirectiveRealValue(APFloat::IEEEdouble);
990
991     if (IDVal == ".align") {
992       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
993       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
994     }
995     if (IDVal == ".align32") {
996       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
997       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
998     }
999     if (IDVal == ".balign")
1000       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1001     if (IDVal == ".balignw")
1002       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1003     if (IDVal == ".balignl")
1004       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1005     if (IDVal == ".p2align")
1006       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1007     if (IDVal == ".p2alignw")
1008       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1009     if (IDVal == ".p2alignl")
1010       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1011
1012     if (IDVal == ".org")
1013       return ParseDirectiveOrg();
1014
1015     if (IDVal == ".fill")
1016       return ParseDirectiveFill();
1017     if (IDVal == ".space")
1018       return ParseDirectiveSpace();
1019     if (IDVal == ".zero")
1020       return ParseDirectiveZero();
1021
1022     // Symbol attribute directives
1023
1024     if (IDVal == ".globl" || IDVal == ".global")
1025       return ParseDirectiveSymbolAttribute(MCSA_Global);
1026     // ELF only? Should it be here?
1027     if (IDVal == ".local")
1028       return ParseDirectiveSymbolAttribute(MCSA_Local);
1029     if (IDVal == ".hidden")
1030       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1031     if (IDVal == ".indirect_symbol")
1032       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1033     if (IDVal == ".internal")
1034       return ParseDirectiveSymbolAttribute(MCSA_Internal);
1035     if (IDVal == ".lazy_reference")
1036       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1037     if (IDVal == ".no_dead_strip")
1038       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1039     if (IDVal == ".symbol_resolver")
1040       return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1041     if (IDVal == ".private_extern")
1042       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1043     if (IDVal == ".protected")
1044       return ParseDirectiveSymbolAttribute(MCSA_Protected);
1045     if (IDVal == ".reference")
1046       return ParseDirectiveSymbolAttribute(MCSA_Reference);
1047     if (IDVal == ".weak")
1048       return ParseDirectiveSymbolAttribute(MCSA_Weak);
1049     if (IDVal == ".weak_definition")
1050       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1051     if (IDVal == ".weak_reference")
1052       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1053     if (IDVal == ".weak_def_can_be_hidden")
1054       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1055
1056     if (IDVal == ".comm")
1057       return ParseDirectiveComm(/*IsLocal=*/false);
1058     if (IDVal == ".lcomm")
1059       return ParseDirectiveComm(/*IsLocal=*/true);
1060
1061     if (IDVal == ".abort")
1062       return ParseDirectiveAbort();
1063     if (IDVal == ".include")
1064       return ParseDirectiveInclude();
1065
1066     // Look up the handler in the handler table.
1067     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1068       DirectiveMap.lookup(IDVal);
1069     if (Handler.first)
1070       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1071
1072     // Target hook for parsing target specific directives.
1073     if (!getTargetParser().ParseDirective(ID))
1074       return false;
1075
1076     Warning(IDLoc, "ignoring directive for now");
1077     EatToEndOfStatement();
1078     return false;
1079   }
1080
1081   CheckForValidSection();
1082
1083   // Canonicalize the opcode to lower case.
1084   SmallString<128> Opcode;
1085   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1086     Opcode.push_back(tolower(IDVal[i]));
1087
1088   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1089   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1090                                                      ParsedOperands);
1091
1092   // Dump the parsed representation, if requested.
1093   if (getShowParsedOperands()) {
1094     SmallString<256> Str;
1095     raw_svector_ostream OS(Str);
1096     OS << "parsed instruction: [";
1097     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1098       if (i != 0)
1099         OS << ", ";
1100       ParsedOperands[i]->dump(OS);
1101     }
1102     OS << "]";
1103
1104     PrintMessage(IDLoc, OS.str(), "note");
1105   }
1106
1107   // If parsing succeeded, match the instruction.
1108   if (!HadError)
1109     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1110                                                          Out);
1111
1112   // Free any parsed operands.
1113   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1114     delete ParsedOperands[i];
1115
1116   // Don't skip the rest of the line, the instruction parser is responsible for
1117   // that.
1118   return false;
1119 }
1120
1121 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1122                                    const std::vector<std::vector<AsmToken> > &A)
1123   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1124 {
1125   // Macro instantiation is lexical, unfortunately. We construct a new buffer
1126   // to hold the macro body with substitutions.
1127   SmallString<256> Buf;
1128   raw_svector_ostream OS(Buf);
1129
1130   StringRef Body = M->Body;
1131   while (!Body.empty()) {
1132     // Scan for the next substitution.
1133     std::size_t End = Body.size(), Pos = 0;
1134     for (; Pos != End; ++Pos) {
1135       // Check for a substitution or escape.
1136       if (Body[Pos] != '$' || Pos + 1 == End)
1137         continue;
1138
1139       char Next = Body[Pos + 1];
1140       if (Next == '$' || Next == 'n' || isdigit(Next))
1141         break;
1142     }
1143
1144     // Add the prefix.
1145     OS << Body.slice(0, Pos);
1146
1147     // Check if we reached the end.
1148     if (Pos == End)
1149       break;
1150
1151     switch (Body[Pos+1]) {
1152        // $$ => $
1153     case '$':
1154       OS << '$';
1155       break;
1156
1157       // $n => number of arguments
1158     case 'n':
1159       OS << A.size();
1160       break;
1161
1162        // $[0-9] => argument
1163     default: {
1164       // Missing arguments are ignored.
1165       unsigned Index = Body[Pos+1] - '0';
1166       if (Index >= A.size())
1167         break;
1168
1169       // Otherwise substitute with the token values, with spaces eliminated.
1170       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1171              ie = A[Index].end(); it != ie; ++it)
1172         OS << it->getString();
1173       break;
1174     }
1175     }
1176
1177     // Update the scan point.
1178     Body = Body.substr(Pos + 2);
1179   }
1180
1181   // We include the .endmacro in the buffer as our queue to exit the macro
1182   // instantiation.
1183   OS << ".endmacro\n";
1184
1185   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1186 }
1187
1188 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1189                                  const Macro *M) {
1190   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1191   // this, although we should protect against infinite loops.
1192   if (ActiveMacros.size() == 20)
1193     return TokError("macros cannot be nested more than 20 levels deep");
1194
1195   // Parse the macro instantiation arguments.
1196   std::vector<std::vector<AsmToken> > MacroArguments;
1197   MacroArguments.push_back(std::vector<AsmToken>());
1198   unsigned ParenLevel = 0;
1199   for (;;) {
1200     if (Lexer.is(AsmToken::Eof))
1201       return TokError("unexpected token in macro instantiation");
1202     if (Lexer.is(AsmToken::EndOfStatement))
1203       break;
1204
1205     // If we aren't inside parentheses and this is a comma, start a new token
1206     // list.
1207     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1208       MacroArguments.push_back(std::vector<AsmToken>());
1209     } else {
1210       // Adjust the current parentheses level.
1211       if (Lexer.is(AsmToken::LParen))
1212         ++ParenLevel;
1213       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1214         --ParenLevel;
1215
1216       // Append the token to the current argument list.
1217       MacroArguments.back().push_back(getTok());
1218     }
1219     Lex();
1220   }
1221
1222   // Create the macro instantiation object and add to the current macro
1223   // instantiation stack.
1224   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1225                                                   getTok().getLoc(),
1226                                                   MacroArguments);
1227   ActiveMacros.push_back(MI);
1228
1229   // Jump to the macro instantiation and prime the lexer.
1230   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1231   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1232   Lex();
1233
1234   return false;
1235 }
1236
1237 void AsmParser::HandleMacroExit() {
1238   // Jump to the EndOfStatement we should return to, and consume it.
1239   JumpToLoc(ActiveMacros.back()->ExitLoc);
1240   Lex();
1241
1242   // Pop the instantiation entry.
1243   delete ActiveMacros.back();
1244   ActiveMacros.pop_back();
1245 }
1246
1247 static void MarkUsed(const MCExpr *Value) {
1248   switch (Value->getKind()) {
1249   case MCExpr::Binary:
1250     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1251     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1252     break;
1253   case MCExpr::Target:
1254   case MCExpr::Constant:
1255     break;
1256   case MCExpr::SymbolRef: {
1257     static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1258     break;
1259   }
1260   case MCExpr::Unary:
1261     MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1262     break;
1263   }
1264 }
1265
1266 bool AsmParser::ParseAssignment(StringRef Name) {
1267   // FIXME: Use better location, we should use proper tokens.
1268   SMLoc EqualLoc = Lexer.getLoc();
1269
1270   const MCExpr *Value;
1271   if (ParseExpression(Value))
1272     return true;
1273
1274   MarkUsed(Value);
1275
1276   if (Lexer.isNot(AsmToken::EndOfStatement))
1277     return TokError("unexpected token in assignment");
1278
1279   // Eat the end of statement marker.
1280   Lex();
1281
1282   // Validate that the LHS is allowed to be a variable (either it has not been
1283   // used as a symbol, or it is an absolute symbol).
1284   MCSymbol *Sym = getContext().LookupSymbol(Name);
1285   if (Sym) {
1286     // Diagnose assignment to a label.
1287     //
1288     // FIXME: Diagnostics. Note the location of the definition as a label.
1289     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1290     if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1291       ; // Allow redefinitions of undefined symbols only used in directives.
1292     else if (!Sym->isUndefined() && !Sym->isAbsolute())
1293       return Error(EqualLoc, "redefinition of '" + Name + "'");
1294     else if (!Sym->isVariable())
1295       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1296     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1297       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1298                    Name + "'");
1299
1300     // Don't count these checks as uses.
1301     Sym->setUsed(false);
1302   } else
1303     Sym = getContext().GetOrCreateSymbol(Name);
1304
1305   // FIXME: Handle '.'.
1306
1307   // Do the assignment.
1308   Out.EmitAssignment(Sym, Value);
1309
1310   return false;
1311 }
1312
1313 /// ParseIdentifier:
1314 ///   ::= identifier
1315 ///   ::= string
1316 bool AsmParser::ParseIdentifier(StringRef &Res) {
1317   // The assembler has relaxed rules for accepting identifiers, in particular we
1318   // allow things like '.globl $foo', which would normally be separate
1319   // tokens. At this level, we have already lexed so we cannot (currently)
1320   // handle this as a context dependent token, instead we detect adjacent tokens
1321   // and return the combined identifier.
1322   if (Lexer.is(AsmToken::Dollar)) {
1323     SMLoc DollarLoc = getLexer().getLoc();
1324
1325     // Consume the dollar sign, and check for a following identifier.
1326     Lex();
1327     if (Lexer.isNot(AsmToken::Identifier))
1328       return true;
1329
1330     // We have a '$' followed by an identifier, make sure they are adjacent.
1331     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1332       return true;
1333
1334     // Construct the joined identifier and consume the token.
1335     Res = StringRef(DollarLoc.getPointer(),
1336                     getTok().getIdentifier().size() + 1);
1337     Lex();
1338     return false;
1339   }
1340
1341   if (Lexer.isNot(AsmToken::Identifier) &&
1342       Lexer.isNot(AsmToken::String))
1343     return true;
1344
1345   Res = getTok().getIdentifier();
1346
1347   Lex(); // Consume the identifier token.
1348
1349   return false;
1350 }
1351
1352 /// ParseDirectiveSet:
1353 ///   ::= .set identifier ',' expression
1354 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1355   StringRef Name;
1356
1357   if (ParseIdentifier(Name))
1358     return TokError("expected identifier after '" + Twine(IDVal) + "'");
1359
1360   if (getLexer().isNot(AsmToken::Comma))
1361     return TokError("unexpected token in '" + Twine(IDVal) + "'");
1362   Lex();
1363
1364   return ParseAssignment(Name);
1365 }
1366
1367 bool AsmParser::ParseEscapedString(std::string &Data) {
1368   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1369
1370   Data = "";
1371   StringRef Str = getTok().getStringContents();
1372   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1373     if (Str[i] != '\\') {
1374       Data += Str[i];
1375       continue;
1376     }
1377
1378     // Recognize escaped characters. Note that this escape semantics currently
1379     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1380     ++i;
1381     if (i == e)
1382       return TokError("unexpected backslash at end of string");
1383
1384     // Recognize octal sequences.
1385     if ((unsigned) (Str[i] - '0') <= 7) {
1386       // Consume up to three octal characters.
1387       unsigned Value = Str[i] - '0';
1388
1389       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1390         ++i;
1391         Value = Value * 8 + (Str[i] - '0');
1392
1393         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1394           ++i;
1395           Value = Value * 8 + (Str[i] - '0');
1396         }
1397       }
1398
1399       if (Value > 255)
1400         return TokError("invalid octal escape sequence (out of range)");
1401
1402       Data += (unsigned char) Value;
1403       continue;
1404     }
1405
1406     // Otherwise recognize individual escapes.
1407     switch (Str[i]) {
1408     default:
1409       // Just reject invalid escape sequences for now.
1410       return TokError("invalid escape sequence (unrecognized character)");
1411
1412     case 'b': Data += '\b'; break;
1413     case 'f': Data += '\f'; break;
1414     case 'n': Data += '\n'; break;
1415     case 'r': Data += '\r'; break;
1416     case 't': Data += '\t'; break;
1417     case '"': Data += '"'; break;
1418     case '\\': Data += '\\'; break;
1419     }
1420   }
1421
1422   return false;
1423 }
1424
1425 /// ParseDirectiveAscii:
1426 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1427 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1428   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1429     CheckForValidSection();
1430
1431     for (;;) {
1432       if (getLexer().isNot(AsmToken::String))
1433         return TokError("expected string in '" + Twine(IDVal) + "' directive");
1434
1435       std::string Data;
1436       if (ParseEscapedString(Data))
1437         return true;
1438
1439       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1440       if (ZeroTerminated)
1441         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1442
1443       Lex();
1444
1445       if (getLexer().is(AsmToken::EndOfStatement))
1446         break;
1447
1448       if (getLexer().isNot(AsmToken::Comma))
1449         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1450       Lex();
1451     }
1452   }
1453
1454   Lex();
1455   return false;
1456 }
1457
1458 /// ParseDirectiveValue
1459 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1460 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1461   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1462     CheckForValidSection();
1463
1464     for (;;) {
1465       const MCExpr *Value;
1466       if (ParseExpression(Value))
1467         return true;
1468
1469       // Special case constant expressions to match code generator.
1470       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1471         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1472       else
1473         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1474
1475       if (getLexer().is(AsmToken::EndOfStatement))
1476         break;
1477
1478       // FIXME: Improve diagnostic.
1479       if (getLexer().isNot(AsmToken::Comma))
1480         return TokError("unexpected token in directive");
1481       Lex();
1482     }
1483   }
1484
1485   Lex();
1486   return false;
1487 }
1488
1489 /// ParseDirectiveRealValue
1490 ///  ::= (.single | .double) [ expression (, expression)* ]
1491 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1492   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1493     CheckForValidSection();
1494
1495     for (;;) {
1496       // We don't truly support arithmetic on floating point expressions, so we
1497       // have to manually parse unary prefixes.
1498       bool IsNeg = false;
1499       if (getLexer().is(AsmToken::Minus)) {
1500         Lex();
1501         IsNeg = true;
1502       } else if (getLexer().is(AsmToken::Plus))
1503         Lex();
1504
1505       if (getLexer().isNot(AsmToken::Integer) &&
1506           getLexer().isNot(AsmToken::Real))
1507         return TokError("unexpected token in directive");
1508
1509       // Convert to an APFloat.
1510       APFloat Value(Semantics);
1511       if (Value.convertFromString(getTok().getString(),
1512                                   APFloat::rmNearestTiesToEven) ==
1513           APFloat::opInvalidOp)
1514         return TokError("invalid floating point literal");
1515       if (IsNeg)
1516         Value.changeSign();
1517
1518       // Consume the numeric token.
1519       Lex();
1520
1521       // Emit the value as an integer.
1522       APInt AsInt = Value.bitcastToAPInt();
1523       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1524                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1525
1526       if (getLexer().is(AsmToken::EndOfStatement))
1527         break;
1528
1529       if (getLexer().isNot(AsmToken::Comma))
1530         return TokError("unexpected token in directive");
1531       Lex();
1532     }
1533   }
1534
1535   Lex();
1536   return false;
1537 }
1538
1539 /// ParseDirectiveSpace
1540 ///  ::= .space expression [ , expression ]
1541 bool AsmParser::ParseDirectiveSpace() {
1542   CheckForValidSection();
1543
1544   int64_t NumBytes;
1545   if (ParseAbsoluteExpression(NumBytes))
1546     return true;
1547
1548   int64_t FillExpr = 0;
1549   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1550     if (getLexer().isNot(AsmToken::Comma))
1551       return TokError("unexpected token in '.space' directive");
1552     Lex();
1553
1554     if (ParseAbsoluteExpression(FillExpr))
1555       return true;
1556
1557     if (getLexer().isNot(AsmToken::EndOfStatement))
1558       return TokError("unexpected token in '.space' directive");
1559   }
1560
1561   Lex();
1562
1563   if (NumBytes <= 0)
1564     return TokError("invalid number of bytes in '.space' directive");
1565
1566   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1567   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1568
1569   return false;
1570 }
1571
1572 /// ParseDirectiveZero
1573 ///  ::= .zero expression
1574 bool AsmParser::ParseDirectiveZero() {
1575   CheckForValidSection();
1576
1577   int64_t NumBytes;
1578   if (ParseAbsoluteExpression(NumBytes))
1579     return true;
1580
1581   int64_t Val = 0;
1582   if (getLexer().is(AsmToken::Comma)) {
1583     Lex();
1584     if (ParseAbsoluteExpression(Val))
1585       return true;
1586   }
1587
1588   if (getLexer().isNot(AsmToken::EndOfStatement))
1589     return TokError("unexpected token in '.zero' directive");
1590
1591   Lex();
1592
1593   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1594
1595   return false;
1596 }
1597
1598 /// ParseDirectiveFill
1599 ///  ::= .fill expression , expression , expression
1600 bool AsmParser::ParseDirectiveFill() {
1601   CheckForValidSection();
1602
1603   int64_t NumValues;
1604   if (ParseAbsoluteExpression(NumValues))
1605     return true;
1606
1607   if (getLexer().isNot(AsmToken::Comma))
1608     return TokError("unexpected token in '.fill' directive");
1609   Lex();
1610
1611   int64_t FillSize;
1612   if (ParseAbsoluteExpression(FillSize))
1613     return true;
1614
1615   if (getLexer().isNot(AsmToken::Comma))
1616     return TokError("unexpected token in '.fill' directive");
1617   Lex();
1618
1619   int64_t FillExpr;
1620   if (ParseAbsoluteExpression(FillExpr))
1621     return true;
1622
1623   if (getLexer().isNot(AsmToken::EndOfStatement))
1624     return TokError("unexpected token in '.fill' directive");
1625
1626   Lex();
1627
1628   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1629     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1630
1631   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1632     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1633
1634   return false;
1635 }
1636
1637 /// ParseDirectiveOrg
1638 ///  ::= .org expression [ , expression ]
1639 bool AsmParser::ParseDirectiveOrg() {
1640   CheckForValidSection();
1641
1642   const MCExpr *Offset;
1643   if (ParseExpression(Offset))
1644     return true;
1645
1646   // Parse optional fill expression.
1647   int64_t FillExpr = 0;
1648   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1649     if (getLexer().isNot(AsmToken::Comma))
1650       return TokError("unexpected token in '.org' directive");
1651     Lex();
1652
1653     if (ParseAbsoluteExpression(FillExpr))
1654       return true;
1655
1656     if (getLexer().isNot(AsmToken::EndOfStatement))
1657       return TokError("unexpected token in '.org' directive");
1658   }
1659
1660   Lex();
1661
1662   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1663   // has to be relative to the current section.
1664   getStreamer().EmitValueToOffset(Offset, FillExpr);
1665
1666   return false;
1667 }
1668
1669 /// ParseDirectiveAlign
1670 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1671 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1672   CheckForValidSection();
1673
1674   SMLoc AlignmentLoc = getLexer().getLoc();
1675   int64_t Alignment;
1676   if (ParseAbsoluteExpression(Alignment))
1677     return true;
1678
1679   SMLoc MaxBytesLoc;
1680   bool HasFillExpr = false;
1681   int64_t FillExpr = 0;
1682   int64_t MaxBytesToFill = 0;
1683   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1684     if (getLexer().isNot(AsmToken::Comma))
1685       return TokError("unexpected token in directive");
1686     Lex();
1687
1688     // The fill expression can be omitted while specifying a maximum number of
1689     // alignment bytes, e.g:
1690     //  .align 3,,4
1691     if (getLexer().isNot(AsmToken::Comma)) {
1692       HasFillExpr = true;
1693       if (ParseAbsoluteExpression(FillExpr))
1694         return true;
1695     }
1696
1697     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1698       if (getLexer().isNot(AsmToken::Comma))
1699         return TokError("unexpected token in directive");
1700       Lex();
1701
1702       MaxBytesLoc = getLexer().getLoc();
1703       if (ParseAbsoluteExpression(MaxBytesToFill))
1704         return true;
1705
1706       if (getLexer().isNot(AsmToken::EndOfStatement))
1707         return TokError("unexpected token in directive");
1708     }
1709   }
1710
1711   Lex();
1712
1713   if (!HasFillExpr)
1714     FillExpr = 0;
1715
1716   // Compute alignment in bytes.
1717   if (IsPow2) {
1718     // FIXME: Diagnose overflow.
1719     if (Alignment >= 32) {
1720       Error(AlignmentLoc, "invalid alignment value");
1721       Alignment = 31;
1722     }
1723
1724     Alignment = 1ULL << Alignment;
1725   }
1726
1727   // Diagnose non-sensical max bytes to align.
1728   if (MaxBytesLoc.isValid()) {
1729     if (MaxBytesToFill < 1) {
1730       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1731             "many bytes, ignoring maximum bytes expression");
1732       MaxBytesToFill = 0;
1733     }
1734
1735     if (MaxBytesToFill >= Alignment) {
1736       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1737               "has no effect");
1738       MaxBytesToFill = 0;
1739     }
1740   }
1741
1742   // Check whether we should use optimal code alignment for this .align
1743   // directive.
1744   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1745   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1746       ValueSize == 1 && UseCodeAlign) {
1747     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1748   } else {
1749     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1750     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1751                                        MaxBytesToFill);
1752   }
1753
1754   return false;
1755 }
1756
1757 /// ParseDirectiveSymbolAttribute
1758 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1759 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1760   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1761     for (;;) {
1762       StringRef Name;
1763
1764       if (ParseIdentifier(Name))
1765         return TokError("expected identifier in directive");
1766
1767       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1768
1769       getStreamer().EmitSymbolAttribute(Sym, Attr);
1770
1771       if (getLexer().is(AsmToken::EndOfStatement))
1772         break;
1773
1774       if (getLexer().isNot(AsmToken::Comma))
1775         return TokError("unexpected token in directive");
1776       Lex();
1777     }
1778   }
1779
1780   Lex();
1781   return false;
1782 }
1783
1784 /// ParseDirectiveComm
1785 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1786 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1787   CheckForValidSection();
1788
1789   SMLoc IDLoc = getLexer().getLoc();
1790   StringRef Name;
1791   if (ParseIdentifier(Name))
1792     return TokError("expected identifier in directive");
1793
1794   // Handle the identifier as the key symbol.
1795   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1796
1797   if (getLexer().isNot(AsmToken::Comma))
1798     return TokError("unexpected token in directive");
1799   Lex();
1800
1801   int64_t Size;
1802   SMLoc SizeLoc = getLexer().getLoc();
1803   if (ParseAbsoluteExpression(Size))
1804     return true;
1805
1806   int64_t Pow2Alignment = 0;
1807   SMLoc Pow2AlignmentLoc;
1808   if (getLexer().is(AsmToken::Comma)) {
1809     Lex();
1810     Pow2AlignmentLoc = getLexer().getLoc();
1811     if (ParseAbsoluteExpression(Pow2Alignment))
1812       return true;
1813
1814     // If this target takes alignments in bytes (not log) validate and convert.
1815     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1816       if (!isPowerOf2_64(Pow2Alignment))
1817         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1818       Pow2Alignment = Log2_64(Pow2Alignment);
1819     }
1820   }
1821
1822   if (getLexer().isNot(AsmToken::EndOfStatement))
1823     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1824
1825   Lex();
1826
1827   // NOTE: a size of zero for a .comm should create a undefined symbol
1828   // but a size of .lcomm creates a bss symbol of size zero.
1829   if (Size < 0)
1830     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1831                  "be less than zero");
1832
1833   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1834   // may internally end up wanting an alignment in bytes.
1835   // FIXME: Diagnose overflow.
1836   if (Pow2Alignment < 0)
1837     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1838                  "alignment, can't be less than zero");
1839
1840   if (!Sym->isUndefined())
1841     return Error(IDLoc, "invalid symbol redefinition");
1842
1843   // '.lcomm' is equivalent to '.zerofill'.
1844   // Create the Symbol as a common or local common with Size and Pow2Alignment
1845   if (IsLocal) {
1846     getStreamer().EmitZerofill(Ctx.getMachOSection(
1847                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1848                                  0, SectionKind::getBSS()),
1849                                Sym, Size, 1 << Pow2Alignment);
1850     return false;
1851   }
1852
1853   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1854   return false;
1855 }
1856
1857 /// ParseDirectiveAbort
1858 ///  ::= .abort [... message ...]
1859 bool AsmParser::ParseDirectiveAbort() {
1860   // FIXME: Use loc from directive.
1861   SMLoc Loc = getLexer().getLoc();
1862
1863   StringRef Str = ParseStringToEndOfStatement();
1864   if (getLexer().isNot(AsmToken::EndOfStatement))
1865     return TokError("unexpected token in '.abort' directive");
1866
1867   Lex();
1868
1869   if (Str.empty())
1870     Error(Loc, ".abort detected. Assembly stopping.");
1871   else
1872     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1873   // FIXME: Actually abort assembly here.
1874
1875   return false;
1876 }
1877
1878 /// ParseDirectiveInclude
1879 ///  ::= .include "filename"
1880 bool AsmParser::ParseDirectiveInclude() {
1881   if (getLexer().isNot(AsmToken::String))
1882     return TokError("expected string in '.include' directive");
1883
1884   std::string Filename = getTok().getString();
1885   SMLoc IncludeLoc = getLexer().getLoc();
1886   Lex();
1887
1888   if (getLexer().isNot(AsmToken::EndOfStatement))
1889     return TokError("unexpected token in '.include' directive");
1890
1891   // Strip the quotes.
1892   Filename = Filename.substr(1, Filename.size()-2);
1893
1894   // Attempt to switch the lexer to the included file before consuming the end
1895   // of statement to avoid losing it when we switch.
1896   if (EnterIncludeFile(Filename)) {
1897     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1898     return true;
1899   }
1900
1901   return false;
1902 }
1903
1904 /// ParseDirectiveIf
1905 /// ::= .if expression
1906 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1907   TheCondStack.push_back(TheCondState);
1908   TheCondState.TheCond = AsmCond::IfCond;
1909   if(TheCondState.Ignore) {
1910     EatToEndOfStatement();
1911   }
1912   else {
1913     int64_t ExprValue;
1914     if (ParseAbsoluteExpression(ExprValue))
1915       return true;
1916
1917     if (getLexer().isNot(AsmToken::EndOfStatement))
1918       return TokError("unexpected token in '.if' directive");
1919
1920     Lex();
1921
1922     TheCondState.CondMet = ExprValue;
1923     TheCondState.Ignore = !TheCondState.CondMet;
1924   }
1925
1926   return false;
1927 }
1928
1929 /// ParseDirectiveElseIf
1930 /// ::= .elseif expression
1931 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1932   if (TheCondState.TheCond != AsmCond::IfCond &&
1933       TheCondState.TheCond != AsmCond::ElseIfCond)
1934       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1935                           " an .elseif");
1936   TheCondState.TheCond = AsmCond::ElseIfCond;
1937
1938   bool LastIgnoreState = false;
1939   if (!TheCondStack.empty())
1940       LastIgnoreState = TheCondStack.back().Ignore;
1941   if (LastIgnoreState || TheCondState.CondMet) {
1942     TheCondState.Ignore = true;
1943     EatToEndOfStatement();
1944   }
1945   else {
1946     int64_t ExprValue;
1947     if (ParseAbsoluteExpression(ExprValue))
1948       return true;
1949
1950     if (getLexer().isNot(AsmToken::EndOfStatement))
1951       return TokError("unexpected token in '.elseif' directive");
1952
1953     Lex();
1954     TheCondState.CondMet = ExprValue;
1955     TheCondState.Ignore = !TheCondState.CondMet;
1956   }
1957
1958   return false;
1959 }
1960
1961 /// ParseDirectiveElse
1962 /// ::= .else
1963 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1964   if (getLexer().isNot(AsmToken::EndOfStatement))
1965     return TokError("unexpected token in '.else' directive");
1966
1967   Lex();
1968
1969   if (TheCondState.TheCond != AsmCond::IfCond &&
1970       TheCondState.TheCond != AsmCond::ElseIfCond)
1971       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1972                           ".elseif");
1973   TheCondState.TheCond = AsmCond::ElseCond;
1974   bool LastIgnoreState = false;
1975   if (!TheCondStack.empty())
1976     LastIgnoreState = TheCondStack.back().Ignore;
1977   if (LastIgnoreState || TheCondState.CondMet)
1978     TheCondState.Ignore = true;
1979   else
1980     TheCondState.Ignore = false;
1981
1982   return false;
1983 }
1984
1985 /// ParseDirectiveEndIf
1986 /// ::= .endif
1987 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1988   if (getLexer().isNot(AsmToken::EndOfStatement))
1989     return TokError("unexpected token in '.endif' directive");
1990
1991   Lex();
1992
1993   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1994       TheCondStack.empty())
1995     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1996                         ".else");
1997   if (!TheCondStack.empty()) {
1998     TheCondState = TheCondStack.back();
1999     TheCondStack.pop_back();
2000   }
2001
2002   return false;
2003 }
2004
2005 /// ParseDirectiveFile
2006 /// ::= .file [number] string
2007 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2008   // FIXME: I'm not sure what this is.
2009   int64_t FileNumber = -1;
2010   SMLoc FileNumberLoc = getLexer().getLoc();
2011   if (getLexer().is(AsmToken::Integer)) {
2012     FileNumber = getTok().getIntVal();
2013     Lex();
2014
2015     if (FileNumber < 1)
2016       return TokError("file number less than one");
2017   }
2018
2019   if (getLexer().isNot(AsmToken::String))
2020     return TokError("unexpected token in '.file' directive");
2021
2022   StringRef Filename = getTok().getString();
2023   Filename = Filename.substr(1, Filename.size()-2);
2024   Lex();
2025
2026   if (getLexer().isNot(AsmToken::EndOfStatement))
2027     return TokError("unexpected token in '.file' directive");
2028
2029   if (FileNumber == -1)
2030     getStreamer().EmitFileDirective(Filename);
2031   else {
2032     if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2033       Error(FileNumberLoc, "file number already allocated");
2034   }
2035
2036   return false;
2037 }
2038
2039 /// ParseDirectiveLine
2040 /// ::= .line [number]
2041 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2042   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2043     if (getLexer().isNot(AsmToken::Integer))
2044       return TokError("unexpected token in '.line' directive");
2045
2046     int64_t LineNumber = getTok().getIntVal();
2047     (void) LineNumber;
2048     Lex();
2049
2050     // FIXME: Do something with the .line.
2051   }
2052
2053   if (getLexer().isNot(AsmToken::EndOfStatement))
2054     return TokError("unexpected token in '.line' directive");
2055
2056   return false;
2057 }
2058
2059
2060 /// ParseDirectiveLoc
2061 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2062 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2063 /// The first number is a file number, must have been previously assigned with
2064 /// a .file directive, the second number is the line number and optionally the
2065 /// third number is a column position (zero if not specified).  The remaining
2066 /// optional items are .loc sub-directives.
2067 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2068
2069   if (getLexer().isNot(AsmToken::Integer))
2070     return TokError("unexpected token in '.loc' directive");
2071   int64_t FileNumber = getTok().getIntVal();
2072   if (FileNumber < 1)
2073     return TokError("file number less than one in '.loc' directive");
2074   if (!getContext().isValidDwarfFileNumber(FileNumber))
2075     return TokError("unassigned file number in '.loc' directive");
2076   Lex();
2077
2078   int64_t LineNumber = 0;
2079   if (getLexer().is(AsmToken::Integer)) {
2080     LineNumber = getTok().getIntVal();
2081     if (LineNumber < 1)
2082       return TokError("line number less than one in '.loc' directive");
2083     Lex();
2084   }
2085
2086   int64_t ColumnPos = 0;
2087   if (getLexer().is(AsmToken::Integer)) {
2088     ColumnPos = getTok().getIntVal();
2089     if (ColumnPos < 0)
2090       return TokError("column position less than zero in '.loc' directive");
2091     Lex();
2092   }
2093
2094   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2095   unsigned Isa = 0;
2096   int64_t Discriminator = 0;
2097   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2098     for (;;) {
2099       if (getLexer().is(AsmToken::EndOfStatement))
2100         break;
2101
2102       StringRef Name;
2103       SMLoc Loc = getTok().getLoc();
2104       if (getParser().ParseIdentifier(Name))
2105         return TokError("unexpected token in '.loc' directive");
2106
2107       if (Name == "basic_block")
2108         Flags |= DWARF2_FLAG_BASIC_BLOCK;
2109       else if (Name == "prologue_end")
2110         Flags |= DWARF2_FLAG_PROLOGUE_END;
2111       else if (Name == "epilogue_begin")
2112         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2113       else if (Name == "is_stmt") {
2114         SMLoc Loc = getTok().getLoc();
2115         const MCExpr *Value;
2116         if (getParser().ParseExpression(Value))
2117           return true;
2118         // The expression must be the constant 0 or 1.
2119         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2120           int Value = MCE->getValue();
2121           if (Value == 0)
2122             Flags &= ~DWARF2_FLAG_IS_STMT;
2123           else if (Value == 1)
2124             Flags |= DWARF2_FLAG_IS_STMT;
2125           else
2126             return Error(Loc, "is_stmt value not 0 or 1");
2127         }
2128         else {
2129           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2130         }
2131       }
2132       else if (Name == "isa") {
2133         SMLoc Loc = getTok().getLoc();
2134         const MCExpr *Value;
2135         if (getParser().ParseExpression(Value))
2136           return true;
2137         // The expression must be a constant greater or equal to 0.
2138         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2139           int Value = MCE->getValue();
2140           if (Value < 0)
2141             return Error(Loc, "isa number less than zero");
2142           Isa = Value;
2143         }
2144         else {
2145           return Error(Loc, "isa number not a constant value");
2146         }
2147       }
2148       else if (Name == "discriminator") {
2149         if (getParser().ParseAbsoluteExpression(Discriminator))
2150           return true;
2151       }
2152       else {
2153         return Error(Loc, "unknown sub-directive in '.loc' directive");
2154       }
2155
2156       if (getLexer().is(AsmToken::EndOfStatement))
2157         break;
2158     }
2159   }
2160
2161   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2162                                       Isa, Discriminator);
2163
2164   return false;
2165 }
2166
2167 /// ParseDirectiveStabs
2168 /// ::= .stabs string, number, number, number
2169 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2170                                            SMLoc DirectiveLoc) {
2171   return TokError("unsupported directive '" + Directive + "'");
2172 }
2173
2174 /// ParseDirectiveCFIStartProc
2175 /// ::= .cfi_startproc
2176 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2177                                                   SMLoc DirectiveLoc) {
2178   return getStreamer().EmitCFIStartProc();
2179 }
2180
2181 /// ParseDirectiveCFIEndProc
2182 /// ::= .cfi_endproc
2183 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2184   return getStreamer().EmitCFIEndProc();
2185 }
2186
2187 /// ParseRegisterOrRegisterNumber - parse register name or number.
2188 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2189                                                      SMLoc DirectiveLoc) {
2190   unsigned RegNo;
2191
2192   if (getLexer().is(AsmToken::Percent)) {
2193     if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2194       DirectiveLoc))
2195       return true;
2196     Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2197   } else
2198     return getParser().ParseAbsoluteExpression(Register);
2199   
2200   return false;
2201 }
2202
2203 /// ParseDirectiveCFIDefCfa
2204 /// ::= .cfi_def_cfa register,  offset
2205 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2206                                                SMLoc DirectiveLoc) {
2207   int64_t Register = 0;
2208   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2209     return true;
2210
2211   if (getLexer().isNot(AsmToken::Comma))
2212     return TokError("unexpected token in directive");
2213   Lex();
2214
2215   int64_t Offset = 0;
2216   if (getParser().ParseAbsoluteExpression(Offset))
2217     return true;
2218
2219   return getStreamer().EmitCFIDefCfa(Register, Offset);
2220 }
2221
2222 /// ParseDirectiveCFIDefCfaOffset
2223 /// ::= .cfi_def_cfa_offset offset
2224 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2225                                                      SMLoc DirectiveLoc) {
2226   int64_t Offset = 0;
2227   if (getParser().ParseAbsoluteExpression(Offset))
2228     return true;
2229
2230   return getStreamer().EmitCFIDefCfaOffset(Offset);
2231 }
2232
2233 /// ParseDirectiveCFIDefCfaRegister
2234 /// ::= .cfi_def_cfa_register register
2235 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2236                                                        SMLoc DirectiveLoc) {
2237   int64_t Register = 0;
2238   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2239     return true;
2240
2241   return getStreamer().EmitCFIDefCfaRegister(Register);
2242 }
2243
2244 /// ParseDirectiveCFIOffset
2245 /// ::= .cfi_off register, offset
2246 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2247   int64_t Register = 0;
2248   int64_t Offset = 0;
2249
2250   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2251     return true;
2252
2253   if (getLexer().isNot(AsmToken::Comma))
2254     return TokError("unexpected token in directive");
2255   Lex();
2256
2257   if (getParser().ParseAbsoluteExpression(Offset))
2258     return true;
2259
2260   return getStreamer().EmitCFIOffset(Register, Offset);
2261 }
2262
2263 static bool isValidEncoding(int64_t Encoding) {
2264   if (Encoding & ~0xff)
2265     return false;
2266
2267   if (Encoding == dwarf::DW_EH_PE_omit)
2268     return true;
2269
2270   const unsigned Format = Encoding & 0xf;
2271   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2272       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2273       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2274       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2275     return false;
2276
2277   const unsigned Application = Encoding & 0x70;
2278   if (Application != dwarf::DW_EH_PE_absptr &&
2279       Application != dwarf::DW_EH_PE_pcrel)
2280     return false;
2281
2282   return true;
2283 }
2284
2285 /// ParseDirectiveCFIPersonalityOrLsda
2286 /// ::= .cfi_personality encoding, [symbol_name]
2287 /// ::= .cfi_lsda encoding, [symbol_name]
2288 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2289                                                     SMLoc DirectiveLoc) {
2290   int64_t Encoding = 0;
2291   if (getParser().ParseAbsoluteExpression(Encoding))
2292     return true;
2293   if (Encoding == dwarf::DW_EH_PE_omit)
2294     return false;
2295
2296   if (!isValidEncoding(Encoding))
2297     return TokError("unsupported encoding.");
2298
2299   if (getLexer().isNot(AsmToken::Comma))
2300     return TokError("unexpected token in directive");
2301   Lex();
2302
2303   StringRef Name;
2304   if (getParser().ParseIdentifier(Name))
2305     return TokError("expected identifier in directive");
2306
2307   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2308
2309   if (IDVal == ".cfi_personality")
2310     return getStreamer().EmitCFIPersonality(Sym, Encoding);
2311   else {
2312     assert(IDVal == ".cfi_lsda");
2313     return getStreamer().EmitCFILsda(Sym, Encoding);
2314   }
2315 }
2316
2317 /// ParseDirectiveCFIRememberState
2318 /// ::= .cfi_remember_state
2319 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2320                                                       SMLoc DirectiveLoc) {
2321   return getStreamer().EmitCFIRememberState();
2322 }
2323
2324 /// ParseDirectiveCFIRestoreState
2325 /// ::= .cfi_remember_state
2326 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2327                                                      SMLoc DirectiveLoc) {
2328   return getStreamer().EmitCFIRestoreState();
2329 }
2330
2331 /// ParseDirectiveMacrosOnOff
2332 /// ::= .macros_on
2333 /// ::= .macros_off
2334 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2335                                                  SMLoc DirectiveLoc) {
2336   if (getLexer().isNot(AsmToken::EndOfStatement))
2337     return Error(getLexer().getLoc(),
2338                  "unexpected token in '" + Directive + "' directive");
2339
2340   getParser().MacrosEnabled = Directive == ".macros_on";
2341
2342   return false;
2343 }
2344
2345 /// ParseDirectiveMacro
2346 /// ::= .macro name
2347 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2348                                            SMLoc DirectiveLoc) {
2349   StringRef Name;
2350   if (getParser().ParseIdentifier(Name))
2351     return TokError("expected identifier in directive");
2352
2353   if (getLexer().isNot(AsmToken::EndOfStatement))
2354     return TokError("unexpected token in '.macro' directive");
2355
2356   // Eat the end of statement.
2357   Lex();
2358
2359   AsmToken EndToken, StartToken = getTok();
2360
2361   // Lex the macro definition.
2362   for (;;) {
2363     // Check whether we have reached the end of the file.
2364     if (getLexer().is(AsmToken::Eof))
2365       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2366
2367     // Otherwise, check whether we have reach the .endmacro.
2368     if (getLexer().is(AsmToken::Identifier) &&
2369         (getTok().getIdentifier() == ".endm" ||
2370          getTok().getIdentifier() == ".endmacro")) {
2371       EndToken = getTok();
2372       Lex();
2373       if (getLexer().isNot(AsmToken::EndOfStatement))
2374         return TokError("unexpected token in '" + EndToken.getIdentifier() +
2375                         "' directive");
2376       break;
2377     }
2378
2379     // Otherwise, scan til the end of the statement.
2380     getParser().EatToEndOfStatement();
2381   }
2382
2383   if (getParser().MacroMap.lookup(Name)) {
2384     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2385   }
2386
2387   const char *BodyStart = StartToken.getLoc().getPointer();
2388   const char *BodyEnd = EndToken.getLoc().getPointer();
2389   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2390   getParser().MacroMap[Name] = new Macro(Name, Body);
2391   return false;
2392 }
2393
2394 /// ParseDirectiveEndMacro
2395 /// ::= .endm
2396 /// ::= .endmacro
2397 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2398                                            SMLoc DirectiveLoc) {
2399   if (getLexer().isNot(AsmToken::EndOfStatement))
2400     return TokError("unexpected token in '" + Directive + "' directive");
2401
2402   // If we are inside a macro instantiation, terminate the current
2403   // instantiation.
2404   if (!getParser().ActiveMacros.empty()) {
2405     getParser().HandleMacroExit();
2406     return false;
2407   }
2408
2409   // Otherwise, this .endmacro is a stray entry in the file; well formed
2410   // .endmacro directives are handled during the macro definition parsing.
2411   return TokError("unexpected '" + Directive + "' in file, "
2412                   "no current macro definition");
2413 }
2414
2415 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2416   getParser().CheckForValidSection();
2417
2418   const MCExpr *Value;
2419
2420   if (getParser().ParseExpression(Value))
2421     return true;
2422
2423   if (getLexer().isNot(AsmToken::EndOfStatement))
2424     return TokError("unexpected token in directive");
2425
2426   if (DirName[1] == 's')
2427     getStreamer().EmitSLEB128Value(Value);
2428   else
2429     getStreamer().EmitULEB128Value(Value);
2430
2431   return false;
2432 }
2433
2434
2435 /// \brief Create an MCAsmParser instance.
2436 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2437                                      MCContext &C, MCStreamer &Out,
2438                                      const MCAsmInfo &MAI) {
2439   return new AsmParser(T, SM, C, Out, MAI);
2440 }