MC/AsmParser: Stop playing unsafe member function pointer calls, this isn't
[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/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.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/Support/Compiler.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmParser.h"
34 #include <vector>
35 using namespace llvm;
36
37 namespace {
38
39 /// \brief Helper class for tracking macro definitions.
40 struct Macro {
41   StringRef Name;
42   StringRef Body;
43
44 public:
45   Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
46 };
47
48 /// \brief Helper class for storing information about an active macro
49 /// instantiation.
50 struct MacroInstantiation {
51   /// The macro being instantiated.
52   const Macro *TheMacro;
53
54   /// The macro instantiation with substitutions.
55   MemoryBuffer *Instantiation;
56
57   /// The location of the instantiation.
58   SMLoc InstantiationLoc;
59
60   /// The location where parsing should resume upon instantiation completion.
61   SMLoc ExitLoc;
62
63 public:
64   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
65                      const std::vector<std::vector<AsmToken> > &A);
66 };
67
68 /// \brief The concrete assembly parser instance.
69 class AsmParser : public MCAsmParser {
70   friend class GenericAsmParser;
71
72   AsmParser(const AsmParser &);   // DO NOT IMPLEMENT
73   void operator=(const AsmParser &);  // DO NOT IMPLEMENT
74 private:
75   AsmLexer Lexer;
76   MCContext &Ctx;
77   MCStreamer &Out;
78   SourceMgr &SrcMgr;
79   MCAsmParserExtension *GenericParser;
80   MCAsmParserExtension *PlatformParser;
81
82   /// This is the current buffer index we're lexing from as managed by the
83   /// SourceMgr object.
84   int CurBuffer;
85
86   AsmCond TheCondState;
87   std::vector<AsmCond> TheCondStack;
88
89   /// DirectiveMap - This is a table handlers for directives.  Each handler is
90   /// invoked after the directive identifier is read and is responsible for
91   /// parsing and validating the rest of the directive.  The handler is passed
92   /// in the directive name and the location of the directive keyword.
93   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
94
95   /// MacroMap - Map of currently defined macros.
96   StringMap<Macro*> MacroMap;
97
98   /// ActiveMacros - Stack of active macro instantiations.
99   std::vector<MacroInstantiation*> ActiveMacros;
100
101   /// Boolean tracking whether macro substitution is enabled.
102   unsigned MacrosEnabled : 1;
103
104 public:
105   AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
106             const MCAsmInfo &MAI);
107   ~AsmParser();
108
109   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
110
111   void AddDirectiveHandler(MCAsmParserExtension *Object,
112                            StringRef Directive,
113                            DirectiveHandler Handler) {
114     DirectiveMap[Directive] = std::make_pair(Object, Handler);
115   }
116
117 public:
118   /// @name MCAsmParser Interface
119   /// {
120
121   virtual SourceMgr &getSourceManager() { return SrcMgr; }
122   virtual MCAsmLexer &getLexer() { return Lexer; }
123   virtual MCContext &getContext() { return Ctx; }
124   virtual MCStreamer &getStreamer() { return Out; }
125
126   virtual void Warning(SMLoc L, const Twine &Meg);
127   virtual bool Error(SMLoc L, const Twine &Msg);
128
129   const AsmToken &Lex();
130
131   bool ParseExpression(const MCExpr *&Res);
132   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
133   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
134   virtual bool ParseAbsoluteExpression(int64_t &Res);
135
136   /// }
137
138 private:
139   bool ParseStatement();
140
141   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
142   void HandleMacroExit();
143
144   void PrintMacroInstantiations();
145   void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
146     
147   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
148   bool EnterIncludeFile(const std::string &Filename);
149
150   /// \brief Reset the current lexer position to that given by \arg Loc. The
151   /// current token is not set; clients should ensure Lex() is called
152   /// subsequently.
153   void JumpToLoc(SMLoc Loc);
154
155   void EatToEndOfStatement();
156
157   /// \brief Parse up to the end of statement and a return the contents from the
158   /// current token until the end of the statement; the current token on exit
159   /// will be either the EndOfStatement or EOF.
160   StringRef ParseStringToEndOfStatement();
161
162   bool ParseAssignment(StringRef Name);
163
164   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
165   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
166   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
167
168   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
169   /// and set \arg Res to the identifier contents.
170   bool ParseIdentifier(StringRef &Res);
171   
172   // Directive Parsing.
173   bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
174   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
175   bool ParseDirectiveFill(); // ".fill"
176   bool ParseDirectiveSpace(); // ".space"
177   bool ParseDirectiveSet(); // ".set"
178   bool ParseDirectiveOrg(); // ".org"
179   // ".align{,32}", ".p2align{,w,l}"
180   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
181
182   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
183   /// accepts a single symbol (which should be a label or an external).
184   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
185   bool ParseDirectiveELFType(); // ELF specific ".type"
186
187   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
188
189   bool ParseDirectiveAbort(); // ".abort"
190   bool ParseDirectiveInclude(); // ".include"
191
192   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
193   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
194   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
195   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
196
197   /// ParseEscapedString - Parse the current token as a string which may include
198   /// escaped characters and return the string contents.
199   bool ParseEscapedString(std::string &Data);
200 };
201
202 /// \brief Generic implementations of directive handling, etc. which is shared
203 /// (or the default, at least) for all assembler parser.
204 class GenericAsmParser : public MCAsmParserExtension {
205   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
206   void AddDirectiveHandler(StringRef Directive) {
207     getParser().AddDirectiveHandler(this, Directive,
208                                     HandleDirective<GenericAsmParser, Handler>);
209   }
210
211 public:
212   GenericAsmParser() {}
213
214   AsmParser &getParser() {
215     return (AsmParser&) this->MCAsmParserExtension::getParser();
216   }
217
218   virtual void Initialize(MCAsmParser &Parser) {
219     // Call the base implementation.
220     this->MCAsmParserExtension::Initialize(Parser);
221
222     // Debugging directives.
223     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
224     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
225     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
226
227     // Macro directives.
228     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
229       ".macros_on");
230     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
231       ".macros_off");
232     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
233     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
234     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
235   }
236
237   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
238   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
239   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
240
241   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
242   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
243   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
244 };
245
246 }
247
248 namespace llvm {
249
250 extern MCAsmParserExtension *createDarwinAsmParser();
251 extern MCAsmParserExtension *createELFAsmParser();
252
253 }
254
255 enum { DEFAULT_ADDRSPACE = 0 };
256
257 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
258                      MCStreamer &_Out, const MCAsmInfo &_MAI)
259   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
260     GenericParser(new GenericAsmParser), PlatformParser(0),
261     CurBuffer(0), MacrosEnabled(true) {
262   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
263
264   // Initialize the generic parser.
265   GenericParser->Initialize(*this);
266
267   // Initialize the platform / file format parser.
268   //
269   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
270   // created.
271   if (_MAI.hasSubsectionsViaSymbols()) {
272     PlatformParser = createDarwinAsmParser();
273     PlatformParser->Initialize(*this);
274   } else {
275     PlatformParser = createELFAsmParser();
276     PlatformParser->Initialize(*this);
277   }
278 }
279
280 AsmParser::~AsmParser() {
281   delete PlatformParser;
282   delete GenericParser;
283 }
284
285 void AsmParser::PrintMacroInstantiations() {
286   // Print the active macro instantiation stack.
287   for (std::vector<MacroInstantiation*>::const_reverse_iterator
288          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
289     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
290                  "note");
291 }
292
293 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
294   PrintMessage(L, Msg.str(), "warning");
295   PrintMacroInstantiations();
296 }
297
298 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
299   PrintMessage(L, Msg.str(), "error");
300   PrintMacroInstantiations();
301   return true;
302 }
303
304 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg, 
305                              const char *Type) const {
306   SrcMgr.PrintMessage(Loc, Msg, Type);
307 }
308                   
309 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
310   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
311   if (NewBuf == -1)
312     return true;
313   
314   CurBuffer = NewBuf;
315   
316   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
317   
318   return false;
319 }
320
321 void AsmParser::JumpToLoc(SMLoc Loc) {
322   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
323   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
324 }
325
326 const AsmToken &AsmParser::Lex() {
327   const AsmToken *tok = &Lexer.Lex();
328   
329   if (tok->is(AsmToken::Eof)) {
330     // If this is the end of an included file, pop the parent file off the
331     // include stack.
332     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
333     if (ParentIncludeLoc != SMLoc()) {
334       JumpToLoc(ParentIncludeLoc);
335       tok = &Lexer.Lex();
336     }
337   }
338     
339   if (tok->is(AsmToken::Error))
340     Error(Lexer.getErrLoc(), Lexer.getErr());
341   
342   return *tok;
343 }
344
345 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
346   // Create the initial section, if requested.
347   //
348   // FIXME: Target hook & command line option for initial section.
349   if (!NoInitialTextSection)
350     Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
351                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
352                                       0, SectionKind::getText()));
353
354   // Prime the lexer.
355   Lex();
356   
357   bool HadError = false;
358   
359   AsmCond StartingCondState = TheCondState;
360
361   // While we have input, parse each statement.
362   while (Lexer.isNot(AsmToken::Eof)) {
363     if (!ParseStatement()) continue;
364   
365     // We had an error, remember it and recover by skipping to the next line.
366     HadError = true;
367     EatToEndOfStatement();
368   }
369
370   if (TheCondState.TheCond != StartingCondState.TheCond ||
371       TheCondState.Ignore != StartingCondState.Ignore)
372     return TokError("unmatched .ifs or .elses");
373   
374   // Finalize the output stream if there are no errors and if the client wants
375   // us to.
376   if (!HadError && !NoFinalize)  
377     Out.Finish();
378
379   return HadError;
380 }
381
382 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
383 void AsmParser::EatToEndOfStatement() {
384   while (Lexer.isNot(AsmToken::EndOfStatement) &&
385          Lexer.isNot(AsmToken::Eof))
386     Lex();
387   
388   // Eat EOL.
389   if (Lexer.is(AsmToken::EndOfStatement))
390     Lex();
391 }
392
393 StringRef AsmParser::ParseStringToEndOfStatement() {
394   const char *Start = getTok().getLoc().getPointer();
395
396   while (Lexer.isNot(AsmToken::EndOfStatement) &&
397          Lexer.isNot(AsmToken::Eof))
398     Lex();
399
400   const char *End = getTok().getLoc().getPointer();
401   return StringRef(Start, End - Start);
402 }
403
404 /// ParseParenExpr - Parse a paren expression and return it.
405 /// NOTE: This assumes the leading '(' has already been consumed.
406 ///
407 /// parenexpr ::= expr)
408 ///
409 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
410   if (ParseExpression(Res)) return true;
411   if (Lexer.isNot(AsmToken::RParen))
412     return TokError("expected ')' in parentheses expression");
413   EndLoc = Lexer.getLoc();
414   Lex();
415   return false;
416 }
417
418 /// ParsePrimaryExpr - Parse a primary expression and return it.
419 ///  primaryexpr ::= (parenexpr
420 ///  primaryexpr ::= symbol
421 ///  primaryexpr ::= number
422 ///  primaryexpr ::= '.'
423 ///  primaryexpr ::= ~,+,- primaryexpr
424 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
425   switch (Lexer.getKind()) {
426   default:
427     return TokError("unknown token in expression");
428   case AsmToken::Exclaim:
429     Lex(); // Eat the operator.
430     if (ParsePrimaryExpr(Res, EndLoc))
431       return true;
432     Res = MCUnaryExpr::CreateLNot(Res, getContext());
433     return false;
434   case AsmToken::String:
435   case AsmToken::Identifier: {
436     // This is a symbol reference.
437     std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
438     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
439
440     // Mark the symbol as used in an expression.
441     Sym->setUsedInExpr(true);
442
443     // Lookup the symbol variant if used.
444     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
445     if (Split.first.size() != getTok().getIdentifier().size())
446       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
447
448     EndLoc = Lexer.getLoc();
449     Lex(); // Eat identifier.
450
451     // If this is an absolute variable reference, substitute it now to preserve
452     // semantics in the face of reassignment.
453     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
454       if (Variant)
455         return Error(EndLoc, "unexpected modified on variable reference");
456
457       Res = Sym->getVariableValue();
458       return false;
459     }
460
461     // Otherwise create a symbol ref.
462     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
463     return false;
464   }
465   case AsmToken::Integer: {
466     SMLoc Loc = getTok().getLoc();
467     int64_t IntVal = getTok().getIntVal();
468     Res = MCConstantExpr::Create(IntVal, getContext());
469     EndLoc = Lexer.getLoc();
470     Lex(); // Eat token.
471     // Look for 'b' or 'f' following an Integer as a directional label
472     if (Lexer.getKind() == AsmToken::Identifier) {
473       StringRef IDVal = getTok().getString();
474       if (IDVal == "f" || IDVal == "b"){
475         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
476                                                       IDVal == "f" ? 1 : 0);
477         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
478                                       getContext());
479         if(IDVal == "b" && Sym->isUndefined())
480           return Error(Loc, "invalid reference to undefined symbol");
481         EndLoc = Lexer.getLoc();
482         Lex(); // Eat identifier.
483       }
484     }
485     return false;
486   }
487   case AsmToken::Dot: {
488     // This is a '.' reference, which references the current PC.  Emit a
489     // temporary label to the streamer and refer to it.
490     MCSymbol *Sym = Ctx.CreateTempSymbol();
491     Out.EmitLabel(Sym);
492     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
493     EndLoc = Lexer.getLoc();
494     Lex(); // Eat identifier.
495     return false;
496   }
497       
498   case AsmToken::LParen:
499     Lex(); // Eat the '('.
500     return ParseParenExpr(Res, EndLoc);
501   case AsmToken::Minus:
502     Lex(); // Eat the operator.
503     if (ParsePrimaryExpr(Res, EndLoc))
504       return true;
505     Res = MCUnaryExpr::CreateMinus(Res, getContext());
506     return false;
507   case AsmToken::Plus:
508     Lex(); // Eat the operator.
509     if (ParsePrimaryExpr(Res, EndLoc))
510       return true;
511     Res = MCUnaryExpr::CreatePlus(Res, getContext());
512     return false;
513   case AsmToken::Tilde:
514     Lex(); // Eat the operator.
515     if (ParsePrimaryExpr(Res, EndLoc))
516       return true;
517     Res = MCUnaryExpr::CreateNot(Res, getContext());
518     return false;
519   }
520 }
521
522 bool AsmParser::ParseExpression(const MCExpr *&Res) {
523   SMLoc EndLoc;
524   return ParseExpression(Res, EndLoc);
525 }
526
527 /// ParseExpression - Parse an expression and return it.
528 /// 
529 ///  expr ::= expr +,- expr          -> lowest.
530 ///  expr ::= expr |,^,&,! expr      -> middle.
531 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
532 ///  expr ::= primaryexpr
533 ///
534 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
535   // Parse the expression.
536   Res = 0;
537   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
538     return true;
539
540   // Try to constant fold it up front, if possible.
541   int64_t Value;
542   if (Res->EvaluateAsAbsolute(Value))
543     Res = MCConstantExpr::Create(Value, getContext());
544
545   return false;
546 }
547
548 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
549   Res = 0;
550   return ParseParenExpr(Res, EndLoc) ||
551          ParseBinOpRHS(1, Res, EndLoc);
552 }
553
554 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
555   const MCExpr *Expr;
556   
557   SMLoc StartLoc = Lexer.getLoc();
558   if (ParseExpression(Expr))
559     return true;
560
561   if (!Expr->EvaluateAsAbsolute(Res))
562     return Error(StartLoc, "expected absolute expression");
563
564   return false;
565 }
566
567 static unsigned getBinOpPrecedence(AsmToken::TokenKind K, 
568                                    MCBinaryExpr::Opcode &Kind) {
569   switch (K) {
570   default:
571     return 0;    // not a binop.
572
573     // Lowest Precedence: &&, ||
574   case AsmToken::AmpAmp:
575     Kind = MCBinaryExpr::LAnd;
576     return 1;
577   case AsmToken::PipePipe:
578     Kind = MCBinaryExpr::LOr;
579     return 1;
580
581     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
582   case AsmToken::Plus:
583     Kind = MCBinaryExpr::Add;
584     return 2;
585   case AsmToken::Minus:
586     Kind = MCBinaryExpr::Sub;
587     return 2;
588   case AsmToken::EqualEqual:
589     Kind = MCBinaryExpr::EQ;
590     return 2;
591   case AsmToken::ExclaimEqual:
592   case AsmToken::LessGreater:
593     Kind = MCBinaryExpr::NE;
594     return 2;
595   case AsmToken::Less:
596     Kind = MCBinaryExpr::LT;
597     return 2;
598   case AsmToken::LessEqual:
599     Kind = MCBinaryExpr::LTE;
600     return 2;
601   case AsmToken::Greater:
602     Kind = MCBinaryExpr::GT;
603     return 2;
604   case AsmToken::GreaterEqual:
605     Kind = MCBinaryExpr::GTE;
606     return 2;
607
608     // Intermediate Precedence: |, &, ^
609     //
610     // FIXME: gas seems to support '!' as an infix operator?
611   case AsmToken::Pipe:
612     Kind = MCBinaryExpr::Or;
613     return 3;
614   case AsmToken::Caret:
615     Kind = MCBinaryExpr::Xor;
616     return 3;
617   case AsmToken::Amp:
618     Kind = MCBinaryExpr::And;
619     return 3;
620
621     // Highest Precedence: *, /, %, <<, >>
622   case AsmToken::Star:
623     Kind = MCBinaryExpr::Mul;
624     return 4;
625   case AsmToken::Slash:
626     Kind = MCBinaryExpr::Div;
627     return 4;
628   case AsmToken::Percent:
629     Kind = MCBinaryExpr::Mod;
630     return 4;
631   case AsmToken::LessLess:
632     Kind = MCBinaryExpr::Shl;
633     return 4;
634   case AsmToken::GreaterGreater:
635     Kind = MCBinaryExpr::Shr;
636     return 4;
637   }
638 }
639
640
641 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
642 /// Res contains the LHS of the expression on input.
643 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
644                               SMLoc &EndLoc) {
645   while (1) {
646     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
647     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
648     
649     // If the next token is lower precedence than we are allowed to eat, return
650     // successfully with what we ate already.
651     if (TokPrec < Precedence)
652       return false;
653     
654     Lex();
655     
656     // Eat the next primary expression.
657     const MCExpr *RHS;
658     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
659     
660     // If BinOp binds less tightly with RHS than the operator after RHS, let
661     // the pending operator take RHS as its LHS.
662     MCBinaryExpr::Opcode Dummy;
663     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
664     if (TokPrec < NextTokPrec) {
665       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
666     }
667
668     // Merge LHS and RHS according to operator.
669     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
670   }
671 }
672
673   
674   
675   
676 /// ParseStatement:
677 ///   ::= EndOfStatement
678 ///   ::= Label* Directive ...Operands... EndOfStatement
679 ///   ::= Label* Identifier OperandList* EndOfStatement
680 bool AsmParser::ParseStatement() {
681   if (Lexer.is(AsmToken::EndOfStatement)) {
682     Out.AddBlankLine();
683     Lex();
684     return false;
685   }
686
687   // Statements always start with an identifier.
688   AsmToken ID = getTok();
689   SMLoc IDLoc = ID.getLoc();
690   StringRef IDVal;
691   int64_t LocalLabelVal = -1;
692   // GUESS allow an integer followed by a ':' as a directional local label
693   if (Lexer.is(AsmToken::Integer)) {
694     LocalLabelVal = getTok().getIntVal();
695     if (LocalLabelVal < 0) {
696       if (!TheCondState.Ignore)
697         return TokError("unexpected token at start of statement");
698       IDVal = "";
699     }
700     else {
701       IDVal = getTok().getString();
702       Lex(); // Consume the integer token to be used as an identifier token.
703       if (Lexer.getKind() != AsmToken::Colon) {
704         if (!TheCondState.Ignore)
705           return TokError("unexpected token at start of statement");
706       }
707     }
708   }
709   else if (ParseIdentifier(IDVal)) {
710     if (!TheCondState.Ignore)
711       return TokError("unexpected token at start of statement");
712     IDVal = "";
713   }
714
715   // Handle conditional assembly here before checking for skipping.  We
716   // have to do this so that .endif isn't skipped in a ".if 0" block for
717   // example.
718   if (IDVal == ".if")
719     return ParseDirectiveIf(IDLoc);
720   if (IDVal == ".elseif")
721     return ParseDirectiveElseIf(IDLoc);
722   if (IDVal == ".else")
723     return ParseDirectiveElse(IDLoc);
724   if (IDVal == ".endif")
725     return ParseDirectiveEndIf(IDLoc);
726     
727   // If we are in a ".if 0" block, ignore this statement.
728   if (TheCondState.Ignore) {
729     EatToEndOfStatement();
730     return false;
731   }
732   
733   // FIXME: Recurse on local labels?
734
735   // See what kind of statement we have.
736   switch (Lexer.getKind()) {
737   case AsmToken::Colon: {
738     // identifier ':'   -> Label.
739     Lex();
740
741     // Diagnose attempt to use a variable as a label.
742     //
743     // FIXME: Diagnostics. Note the location of the definition as a label.
744     // FIXME: This doesn't diagnose assignment to a symbol which has been
745     // implicitly marked as external.
746     MCSymbol *Sym;
747     if (LocalLabelVal == -1)
748       Sym = getContext().GetOrCreateSymbol(IDVal);
749     else
750       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
751     if (!Sym->isUndefined() || Sym->isVariable())
752       return Error(IDLoc, "invalid symbol redefinition");
753     
754     // Emit the label.
755     Out.EmitLabel(Sym);
756    
757     // Consume any end of statement token, if present, to avoid spurious
758     // AddBlankLine calls().
759     if (Lexer.is(AsmToken::EndOfStatement)) {
760       Lex();
761       if (Lexer.is(AsmToken::Eof))
762         return false;
763     }
764
765     return ParseStatement();
766   }
767
768   case AsmToken::Equal:
769     // identifier '=' ... -> assignment statement
770     Lex();
771
772     return ParseAssignment(IDVal);
773
774   default: // Normal instruction or directive.
775     break;
776   }
777
778   // If macros are enabled, check to see if this is a macro instantiation.
779   if (MacrosEnabled)
780     if (const Macro *M = MacroMap.lookup(IDVal))
781       return HandleMacroEntry(IDVal, IDLoc, M);
782
783   // Otherwise, we have a normal instruction or directive.  
784   if (IDVal[0] == '.') {
785     // Assembler features
786     if (IDVal == ".set")
787       return ParseDirectiveSet();
788
789     // Data directives
790
791     if (IDVal == ".ascii")
792       return ParseDirectiveAscii(false);
793     if (IDVal == ".asciz")
794       return ParseDirectiveAscii(true);
795
796     if (IDVal == ".byte")
797       return ParseDirectiveValue(1);
798     if (IDVal == ".short")
799       return ParseDirectiveValue(2);
800     if (IDVal == ".long")
801       return ParseDirectiveValue(4);
802     if (IDVal == ".quad")
803       return ParseDirectiveValue(8);
804
805     // FIXME: Target hooks for IsPow2.
806     if (IDVal == ".align")
807       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
808     if (IDVal == ".align32")
809       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
810     if (IDVal == ".balign")
811       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
812     if (IDVal == ".balignw")
813       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
814     if (IDVal == ".balignl")
815       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
816     if (IDVal == ".p2align")
817       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
818     if (IDVal == ".p2alignw")
819       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
820     if (IDVal == ".p2alignl")
821       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
822
823     if (IDVal == ".org")
824       return ParseDirectiveOrg();
825
826     if (IDVal == ".fill")
827       return ParseDirectiveFill();
828     if (IDVal == ".space")
829       return ParseDirectiveSpace();
830
831     // Symbol attribute directives
832
833     if (IDVal == ".globl" || IDVal == ".global")
834       return ParseDirectiveSymbolAttribute(MCSA_Global);
835     if (IDVal == ".hidden")
836       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
837     if (IDVal == ".indirect_symbol")
838       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
839     if (IDVal == ".internal")
840       return ParseDirectiveSymbolAttribute(MCSA_Internal);
841     if (IDVal == ".lazy_reference")
842       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
843     if (IDVal == ".no_dead_strip")
844       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
845     if (IDVal == ".private_extern")
846       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
847     if (IDVal == ".protected")
848       return ParseDirectiveSymbolAttribute(MCSA_Protected);
849     if (IDVal == ".reference")
850       return ParseDirectiveSymbolAttribute(MCSA_Reference);
851     if (IDVal == ".type")
852       return ParseDirectiveELFType();
853     if (IDVal == ".weak")
854       return ParseDirectiveSymbolAttribute(MCSA_Weak);
855     if (IDVal == ".weak_definition")
856       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
857     if (IDVal == ".weak_reference")
858       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
859     if (IDVal == ".weak_def_can_be_hidden")
860       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
861
862     if (IDVal == ".comm")
863       return ParseDirectiveComm(/*IsLocal=*/false);
864     if (IDVal == ".lcomm")
865       return ParseDirectiveComm(/*IsLocal=*/true);
866
867     if (IDVal == ".abort")
868       return ParseDirectiveAbort();
869     if (IDVal == ".include")
870       return ParseDirectiveInclude();
871
872     // Look up the handler in the handler table.
873     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
874       DirectiveMap.lookup(IDVal);
875     if (Handler.first)
876       return (*Handler.second)(Handler.first, IDVal, IDLoc);
877
878     // Target hook for parsing target specific directives.
879     if (!getTargetParser().ParseDirective(ID))
880       return false;
881
882     Warning(IDLoc, "ignoring directive for now");
883     EatToEndOfStatement();
884     return false;
885   }
886
887   // Canonicalize the opcode to lower case.
888   SmallString<128> Opcode;
889   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
890     Opcode.push_back(tolower(IDVal[i]));
891   
892   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
893   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
894                                                      ParsedOperands);
895   if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
896     HadError = TokError("unexpected token in argument list");
897
898   // If parsing succeeded, match the instruction.
899   if (!HadError) {
900     MCInst Inst;
901     if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
902       // Emit the instruction on success.
903       Out.EmitInstruction(Inst);
904     } else {
905       // Otherwise emit a diagnostic about the match failure and set the error
906       // flag.
907       //
908       // FIXME: We should give nicer diagnostics about the exact failure.
909       Error(IDLoc, "unrecognized instruction");
910       HadError = true;
911     }
912   }
913
914   // If there was no error, consume the end-of-statement token. Otherwise this
915   // will be done by our caller.
916   if (!HadError)
917     Lex();
918
919   // Free any parsed operands.
920   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
921     delete ParsedOperands[i];
922
923   return HadError;
924 }
925
926 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
927                                    const std::vector<std::vector<AsmToken> > &A)
928   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
929 {
930   // Macro instantiation is lexical, unfortunately. We construct a new buffer
931   // to hold the macro body with substitutions.
932   SmallString<256> Buf;
933   raw_svector_ostream OS(Buf);
934
935   StringRef Body = M->Body;
936   while (!Body.empty()) {
937     // Scan for the next substitution.
938     std::size_t End = Body.size(), Pos = 0;
939     for (; Pos != End; ++Pos) {
940       // Check for a substitution or escape.
941       if (Body[Pos] != '$' || Pos + 1 == End)
942         continue;
943
944       char Next = Body[Pos + 1];
945       if (Next == '$' || Next == 'n' || isdigit(Next))
946         break;
947     }
948
949     // Add the prefix.
950     OS << Body.slice(0, Pos);
951
952     // Check if we reached the end.
953     if (Pos == End)
954       break;
955
956     switch (Body[Pos+1]) {
957        // $$ => $
958     case '$':
959       OS << '$';
960       break;
961
962       // $n => number of arguments
963     case 'n':
964       OS << A.size();
965       break;
966
967        // $[0-9] => argument
968     default: {
969       // Missing arguments are ignored.
970       unsigned Index = Body[Pos+1] - '0';
971       if (Index >= A.size())
972         break;
973
974       // Otherwise substitute with the token values, with spaces eliminated.
975       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
976              ie = A[Index].end(); it != ie; ++it)
977         OS << it->getString();
978       break;
979     }
980     }
981
982     // Update the scan point.
983     Body = Body.substr(Pos + 2);
984   }
985
986   // We include the .endmacro in the buffer as our queue to exit the macro
987   // instantiation.
988   OS << ".endmacro\n";
989
990   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
991 }
992
993 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
994                                  const Macro *M) {
995   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
996   // this, although we should protect against infinite loops.
997   if (ActiveMacros.size() == 20)
998     return TokError("macros cannot be nested more than 20 levels deep");
999
1000   // Parse the macro instantiation arguments.
1001   std::vector<std::vector<AsmToken> > MacroArguments;
1002   MacroArguments.push_back(std::vector<AsmToken>());
1003   unsigned ParenLevel = 0;
1004   for (;;) {
1005     if (Lexer.is(AsmToken::Eof))
1006       return TokError("unexpected token in macro instantiation");
1007     if (Lexer.is(AsmToken::EndOfStatement))
1008       break;
1009
1010     // If we aren't inside parentheses and this is a comma, start a new token
1011     // list.
1012     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1013       MacroArguments.push_back(std::vector<AsmToken>());
1014     } else if (Lexer.is(AsmToken::LParen)) {
1015       ++ParenLevel;
1016     } else if (Lexer.is(AsmToken::RParen)) {
1017       if (ParenLevel)
1018         --ParenLevel;
1019     } else {
1020       MacroArguments.back().push_back(getTok());
1021     }
1022     Lex();
1023   }
1024
1025   // Create the macro instantiation object and add to the current macro
1026   // instantiation stack.
1027   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1028                                                   getTok().getLoc(),
1029                                                   MacroArguments);
1030   ActiveMacros.push_back(MI);
1031
1032   // Jump to the macro instantiation and prime the lexer.
1033   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1034   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1035   Lex();
1036
1037   return false;
1038 }
1039
1040 void AsmParser::HandleMacroExit() {
1041   // Jump to the EndOfStatement we should return to, and consume it.
1042   JumpToLoc(ActiveMacros.back()->ExitLoc);
1043   Lex();
1044
1045   // Pop the instantiation entry.
1046   delete ActiveMacros.back();
1047   ActiveMacros.pop_back();
1048 }
1049
1050 bool AsmParser::ParseAssignment(StringRef Name) {
1051   // FIXME: Use better location, we should use proper tokens.
1052   SMLoc EqualLoc = Lexer.getLoc();
1053
1054   const MCExpr *Value;
1055   if (ParseExpression(Value))
1056     return true;
1057   
1058   if (Lexer.isNot(AsmToken::EndOfStatement))
1059     return TokError("unexpected token in assignment");
1060
1061   // Eat the end of statement marker.
1062   Lex();
1063
1064   // Validate that the LHS is allowed to be a variable (either it has not been
1065   // used as a symbol, or it is an absolute symbol).
1066   MCSymbol *Sym = getContext().LookupSymbol(Name);
1067   if (Sym) {
1068     // Diagnose assignment to a label.
1069     //
1070     // FIXME: Diagnostics. Note the location of the definition as a label.
1071     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1072     if (Sym->isUndefined() && !Sym->isUsedInExpr())
1073       ; // Allow redefinitions of undefined symbols only used in directives.
1074     else if (!Sym->isUndefined() && !Sym->isAbsolute())
1075       return Error(EqualLoc, "redefinition of '" + Name + "'");
1076     else if (!Sym->isVariable())
1077       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1078     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1079       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1080                    Name + "'");
1081   } else
1082     Sym = getContext().GetOrCreateSymbol(Name);
1083
1084   // FIXME: Handle '.'.
1085
1086   Sym->setUsedInExpr(true);
1087
1088   // Do the assignment.
1089   Out.EmitAssignment(Sym, Value);
1090
1091   return false;
1092 }
1093
1094 /// ParseIdentifier:
1095 ///   ::= identifier
1096 ///   ::= string
1097 bool AsmParser::ParseIdentifier(StringRef &Res) {
1098   if (Lexer.isNot(AsmToken::Identifier) &&
1099       Lexer.isNot(AsmToken::String))
1100     return true;
1101
1102   Res = getTok().getIdentifier();
1103
1104   Lex(); // Consume the identifier token.
1105
1106   return false;
1107 }
1108
1109 /// ParseDirectiveSet:
1110 ///   ::= .set identifier ',' expression
1111 bool AsmParser::ParseDirectiveSet() {
1112   StringRef Name;
1113
1114   if (ParseIdentifier(Name))
1115     return TokError("expected identifier after '.set' directive");
1116   
1117   if (getLexer().isNot(AsmToken::Comma))
1118     return TokError("unexpected token in '.set'");
1119   Lex();
1120
1121   return ParseAssignment(Name);
1122 }
1123
1124 bool AsmParser::ParseEscapedString(std::string &Data) {
1125   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1126
1127   Data = "";
1128   StringRef Str = getTok().getStringContents();
1129   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1130     if (Str[i] != '\\') {
1131       Data += Str[i];
1132       continue;
1133     }
1134
1135     // Recognize escaped characters. Note that this escape semantics currently
1136     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1137     ++i;
1138     if (i == e)
1139       return TokError("unexpected backslash at end of string");
1140
1141     // Recognize octal sequences.
1142     if ((unsigned) (Str[i] - '0') <= 7) {
1143       // Consume up to three octal characters.
1144       unsigned Value = Str[i] - '0';
1145
1146       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1147         ++i;
1148         Value = Value * 8 + (Str[i] - '0');
1149
1150         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1151           ++i;
1152           Value = Value * 8 + (Str[i] - '0');
1153         }
1154       }
1155
1156       if (Value > 255)
1157         return TokError("invalid octal escape sequence (out of range)");
1158
1159       Data += (unsigned char) Value;
1160       continue;
1161     }
1162
1163     // Otherwise recognize individual escapes.
1164     switch (Str[i]) {
1165     default:
1166       // Just reject invalid escape sequences for now.
1167       return TokError("invalid escape sequence (unrecognized character)");
1168
1169     case 'b': Data += '\b'; break;
1170     case 'f': Data += '\f'; break;
1171     case 'n': Data += '\n'; break;
1172     case 'r': Data += '\r'; break;
1173     case 't': Data += '\t'; break;
1174     case '"': Data += '"'; break;
1175     case '\\': Data += '\\'; break;
1176     }
1177   }
1178
1179   return false;
1180 }
1181
1182 /// ParseDirectiveAscii:
1183 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1184 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1185   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1186     for (;;) {
1187       if (getLexer().isNot(AsmToken::String))
1188         return TokError("expected string in '.ascii' or '.asciz' directive");
1189
1190       std::string Data;
1191       if (ParseEscapedString(Data))
1192         return true;
1193
1194       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1195       if (ZeroTerminated)
1196         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1197
1198       Lex();
1199
1200       if (getLexer().is(AsmToken::EndOfStatement))
1201         break;
1202
1203       if (getLexer().isNot(AsmToken::Comma))
1204         return TokError("unexpected token in '.ascii' or '.asciz' directive");
1205       Lex();
1206     }
1207   }
1208
1209   Lex();
1210   return false;
1211 }
1212
1213 /// ParseDirectiveValue
1214 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1215 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1216   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1217     for (;;) {
1218       const MCExpr *Value;
1219       SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1220       if (ParseExpression(Value))
1221         return true;
1222
1223       // Special case constant expressions to match code generator.
1224       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1225         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1226       else
1227         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1228
1229       if (getLexer().is(AsmToken::EndOfStatement))
1230         break;
1231       
1232       // FIXME: Improve diagnostic.
1233       if (getLexer().isNot(AsmToken::Comma))
1234         return TokError("unexpected token in directive");
1235       Lex();
1236     }
1237   }
1238
1239   Lex();
1240   return false;
1241 }
1242
1243 /// ParseDirectiveSpace
1244 ///  ::= .space expression [ , expression ]
1245 bool AsmParser::ParseDirectiveSpace() {
1246   int64_t NumBytes;
1247   if (ParseAbsoluteExpression(NumBytes))
1248     return true;
1249
1250   int64_t FillExpr = 0;
1251   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1252     if (getLexer().isNot(AsmToken::Comma))
1253       return TokError("unexpected token in '.space' directive");
1254     Lex();
1255     
1256     if (ParseAbsoluteExpression(FillExpr))
1257       return true;
1258
1259     if (getLexer().isNot(AsmToken::EndOfStatement))
1260       return TokError("unexpected token in '.space' directive");
1261   }
1262
1263   Lex();
1264
1265   if (NumBytes <= 0)
1266     return TokError("invalid number of bytes in '.space' directive");
1267
1268   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1269   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1270
1271   return false;
1272 }
1273
1274 /// ParseDirectiveFill
1275 ///  ::= .fill expression , expression , expression
1276 bool AsmParser::ParseDirectiveFill() {
1277   int64_t NumValues;
1278   if (ParseAbsoluteExpression(NumValues))
1279     return true;
1280
1281   if (getLexer().isNot(AsmToken::Comma))
1282     return TokError("unexpected token in '.fill' directive");
1283   Lex();
1284   
1285   int64_t FillSize;
1286   if (ParseAbsoluteExpression(FillSize))
1287     return true;
1288
1289   if (getLexer().isNot(AsmToken::Comma))
1290     return TokError("unexpected token in '.fill' directive");
1291   Lex();
1292   
1293   int64_t FillExpr;
1294   if (ParseAbsoluteExpression(FillExpr))
1295     return true;
1296
1297   if (getLexer().isNot(AsmToken::EndOfStatement))
1298     return TokError("unexpected token in '.fill' directive");
1299   
1300   Lex();
1301
1302   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1303     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1304
1305   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1306     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1307
1308   return false;
1309 }
1310
1311 /// ParseDirectiveOrg
1312 ///  ::= .org expression [ , expression ]
1313 bool AsmParser::ParseDirectiveOrg() {
1314   const MCExpr *Offset;
1315   if (ParseExpression(Offset))
1316     return true;
1317
1318   // Parse optional fill expression.
1319   int64_t FillExpr = 0;
1320   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1321     if (getLexer().isNot(AsmToken::Comma))
1322       return TokError("unexpected token in '.org' directive");
1323     Lex();
1324     
1325     if (ParseAbsoluteExpression(FillExpr))
1326       return true;
1327
1328     if (getLexer().isNot(AsmToken::EndOfStatement))
1329       return TokError("unexpected token in '.org' directive");
1330   }
1331
1332   Lex();
1333
1334   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1335   // has to be relative to the current section.
1336   getStreamer().EmitValueToOffset(Offset, FillExpr);
1337
1338   return false;
1339 }
1340
1341 /// ParseDirectiveAlign
1342 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1343 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1344   SMLoc AlignmentLoc = getLexer().getLoc();
1345   int64_t Alignment;
1346   if (ParseAbsoluteExpression(Alignment))
1347     return true;
1348
1349   SMLoc MaxBytesLoc;
1350   bool HasFillExpr = false;
1351   int64_t FillExpr = 0;
1352   int64_t MaxBytesToFill = 0;
1353   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1354     if (getLexer().isNot(AsmToken::Comma))
1355       return TokError("unexpected token in directive");
1356     Lex();
1357
1358     // The fill expression can be omitted while specifying a maximum number of
1359     // alignment bytes, e.g:
1360     //  .align 3,,4
1361     if (getLexer().isNot(AsmToken::Comma)) {
1362       HasFillExpr = true;
1363       if (ParseAbsoluteExpression(FillExpr))
1364         return true;
1365     }
1366
1367     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1368       if (getLexer().isNot(AsmToken::Comma))
1369         return TokError("unexpected token in directive");
1370       Lex();
1371
1372       MaxBytesLoc = getLexer().getLoc();
1373       if (ParseAbsoluteExpression(MaxBytesToFill))
1374         return true;
1375       
1376       if (getLexer().isNot(AsmToken::EndOfStatement))
1377         return TokError("unexpected token in directive");
1378     }
1379   }
1380
1381   Lex();
1382
1383   if (!HasFillExpr)
1384     FillExpr = 0;
1385
1386   // Compute alignment in bytes.
1387   if (IsPow2) {
1388     // FIXME: Diagnose overflow.
1389     if (Alignment >= 32) {
1390       Error(AlignmentLoc, "invalid alignment value");
1391       Alignment = 31;
1392     }
1393
1394     Alignment = 1ULL << Alignment;
1395   }
1396
1397   // Diagnose non-sensical max bytes to align.
1398   if (MaxBytesLoc.isValid()) {
1399     if (MaxBytesToFill < 1) {
1400       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1401             "many bytes, ignoring maximum bytes expression");
1402       MaxBytesToFill = 0;
1403     }
1404
1405     if (MaxBytesToFill >= Alignment) {
1406       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1407               "has no effect");
1408       MaxBytesToFill = 0;
1409     }
1410   }
1411
1412   // Check whether we should use optimal code alignment for this .align
1413   // directive.
1414   //
1415   // FIXME: This should be using a target hook.
1416   bool UseCodeAlign = false;
1417   if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1418         getStreamer().getCurrentSection()))
1419     UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1420   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1421       ValueSize == 1 && UseCodeAlign) {
1422     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1423   } else {
1424     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1425     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1426                                        MaxBytesToFill);
1427   }
1428
1429   return false;
1430 }
1431
1432 /// ParseDirectiveSymbolAttribute
1433 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1434 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1435   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1436     for (;;) {
1437       StringRef Name;
1438
1439       if (ParseIdentifier(Name))
1440         return TokError("expected identifier in directive");
1441       
1442       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1443
1444       getStreamer().EmitSymbolAttribute(Sym, Attr);
1445
1446       if (getLexer().is(AsmToken::EndOfStatement))
1447         break;
1448
1449       if (getLexer().isNot(AsmToken::Comma))
1450         return TokError("unexpected token in directive");
1451       Lex();
1452     }
1453   }
1454
1455   Lex();
1456   return false;  
1457 }
1458
1459 /// ParseDirectiveELFType
1460 ///  ::= .type identifier , @attribute
1461 bool AsmParser::ParseDirectiveELFType() {
1462   StringRef Name;
1463   if (ParseIdentifier(Name))
1464     return TokError("expected identifier in directive");
1465
1466   // Handle the identifier as the key symbol.
1467   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1468
1469   if (getLexer().isNot(AsmToken::Comma))
1470     return TokError("unexpected token in '.type' directive");
1471   Lex();
1472
1473   if (getLexer().isNot(AsmToken::At))
1474     return TokError("expected '@' before type");
1475   Lex();
1476
1477   StringRef Type;
1478   SMLoc TypeLoc;
1479
1480   TypeLoc = getLexer().getLoc();
1481   if (ParseIdentifier(Type))
1482     return TokError("expected symbol type in directive");
1483
1484   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1485     .Case("function", MCSA_ELF_TypeFunction)
1486     .Case("object", MCSA_ELF_TypeObject)
1487     .Case("tls_object", MCSA_ELF_TypeTLS)
1488     .Case("common", MCSA_ELF_TypeCommon)
1489     .Case("notype", MCSA_ELF_TypeNoType)
1490     .Default(MCSA_Invalid);
1491
1492   if (Attr == MCSA_Invalid)
1493     return Error(TypeLoc, "unsupported attribute in '.type' directive");
1494
1495   if (getLexer().isNot(AsmToken::EndOfStatement))
1496     return TokError("unexpected token in '.type' directive");
1497
1498   Lex();
1499
1500   getStreamer().EmitSymbolAttribute(Sym, Attr);
1501
1502   return false;
1503 }
1504
1505 /// ParseDirectiveComm
1506 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1507 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1508   SMLoc IDLoc = getLexer().getLoc();
1509   StringRef Name;
1510   if (ParseIdentifier(Name))
1511     return TokError("expected identifier in directive");
1512   
1513   // Handle the identifier as the key symbol.
1514   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1515
1516   if (getLexer().isNot(AsmToken::Comma))
1517     return TokError("unexpected token in directive");
1518   Lex();
1519
1520   int64_t Size;
1521   SMLoc SizeLoc = getLexer().getLoc();
1522   if (ParseAbsoluteExpression(Size))
1523     return true;
1524
1525   int64_t Pow2Alignment = 0;
1526   SMLoc Pow2AlignmentLoc;
1527   if (getLexer().is(AsmToken::Comma)) {
1528     Lex();
1529     Pow2AlignmentLoc = getLexer().getLoc();
1530     if (ParseAbsoluteExpression(Pow2Alignment))
1531       return true;
1532     
1533     // If this target takes alignments in bytes (not log) validate and convert.
1534     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1535       if (!isPowerOf2_64(Pow2Alignment))
1536         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1537       Pow2Alignment = Log2_64(Pow2Alignment);
1538     }
1539   }
1540   
1541   if (getLexer().isNot(AsmToken::EndOfStatement))
1542     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1543   
1544   Lex();
1545
1546   // NOTE: a size of zero for a .comm should create a undefined symbol
1547   // but a size of .lcomm creates a bss symbol of size zero.
1548   if (Size < 0)
1549     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1550                  "be less than zero");
1551
1552   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1553   // may internally end up wanting an alignment in bytes.
1554   // FIXME: Diagnose overflow.
1555   if (Pow2Alignment < 0)
1556     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1557                  "alignment, can't be less than zero");
1558
1559   if (!Sym->isUndefined())
1560     return Error(IDLoc, "invalid symbol redefinition");
1561
1562   // '.lcomm' is equivalent to '.zerofill'.
1563   // Create the Symbol as a common or local common with Size and Pow2Alignment
1564   if (IsLocal) {
1565     getStreamer().EmitZerofill(Ctx.getMachOSection(
1566                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1567                                  0, SectionKind::getBSS()),
1568                                Sym, Size, 1 << Pow2Alignment);
1569     return false;
1570   }
1571
1572   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1573   return false;
1574 }
1575
1576 /// ParseDirectiveAbort
1577 ///  ::= .abort [... message ...]
1578 bool AsmParser::ParseDirectiveAbort() {
1579   // FIXME: Use loc from directive.
1580   SMLoc Loc = getLexer().getLoc();
1581
1582   StringRef Str = ParseStringToEndOfStatement();
1583   if (getLexer().isNot(AsmToken::EndOfStatement))
1584     return TokError("unexpected token in '.abort' directive");
1585
1586   Lex();
1587
1588   if (Str.empty())
1589     Error(Loc, ".abort detected. Assembly stopping.");
1590   else
1591     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1592   // FIXME: Actually abort assembly here.
1593
1594   return false;
1595 }
1596
1597 /// ParseDirectiveInclude
1598 ///  ::= .include "filename"
1599 bool AsmParser::ParseDirectiveInclude() {
1600   if (getLexer().isNot(AsmToken::String))
1601     return TokError("expected string in '.include' directive");
1602   
1603   std::string Filename = getTok().getString();
1604   SMLoc IncludeLoc = getLexer().getLoc();
1605   Lex();
1606
1607   if (getLexer().isNot(AsmToken::EndOfStatement))
1608     return TokError("unexpected token in '.include' directive");
1609   
1610   // Strip the quotes.
1611   Filename = Filename.substr(1, Filename.size()-2);
1612   
1613   // Attempt to switch the lexer to the included file before consuming the end
1614   // of statement to avoid losing it when we switch.
1615   if (EnterIncludeFile(Filename)) {
1616     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1617     return true;
1618   }
1619
1620   return false;
1621 }
1622
1623 /// ParseDirectiveIf
1624 /// ::= .if expression
1625 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1626   TheCondStack.push_back(TheCondState);
1627   TheCondState.TheCond = AsmCond::IfCond;
1628   if(TheCondState.Ignore) {
1629     EatToEndOfStatement();
1630   }
1631   else {
1632     int64_t ExprValue;
1633     if (ParseAbsoluteExpression(ExprValue))
1634       return true;
1635
1636     if (getLexer().isNot(AsmToken::EndOfStatement))
1637       return TokError("unexpected token in '.if' directive");
1638     
1639     Lex();
1640
1641     TheCondState.CondMet = ExprValue;
1642     TheCondState.Ignore = !TheCondState.CondMet;
1643   }
1644
1645   return false;
1646 }
1647
1648 /// ParseDirectiveElseIf
1649 /// ::= .elseif expression
1650 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1651   if (TheCondState.TheCond != AsmCond::IfCond &&
1652       TheCondState.TheCond != AsmCond::ElseIfCond)
1653       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1654                           " an .elseif");
1655   TheCondState.TheCond = AsmCond::ElseIfCond;
1656
1657   bool LastIgnoreState = false;
1658   if (!TheCondStack.empty())
1659       LastIgnoreState = TheCondStack.back().Ignore;
1660   if (LastIgnoreState || TheCondState.CondMet) {
1661     TheCondState.Ignore = true;
1662     EatToEndOfStatement();
1663   }
1664   else {
1665     int64_t ExprValue;
1666     if (ParseAbsoluteExpression(ExprValue))
1667       return true;
1668
1669     if (getLexer().isNot(AsmToken::EndOfStatement))
1670       return TokError("unexpected token in '.elseif' directive");
1671     
1672     Lex();
1673     TheCondState.CondMet = ExprValue;
1674     TheCondState.Ignore = !TheCondState.CondMet;
1675   }
1676
1677   return false;
1678 }
1679
1680 /// ParseDirectiveElse
1681 /// ::= .else
1682 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1683   if (getLexer().isNot(AsmToken::EndOfStatement))
1684     return TokError("unexpected token in '.else' directive");
1685   
1686   Lex();
1687
1688   if (TheCondState.TheCond != AsmCond::IfCond &&
1689       TheCondState.TheCond != AsmCond::ElseIfCond)
1690       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1691                           ".elseif");
1692   TheCondState.TheCond = AsmCond::ElseCond;
1693   bool LastIgnoreState = false;
1694   if (!TheCondStack.empty())
1695     LastIgnoreState = TheCondStack.back().Ignore;
1696   if (LastIgnoreState || TheCondState.CondMet)
1697     TheCondState.Ignore = true;
1698   else
1699     TheCondState.Ignore = false;
1700
1701   return false;
1702 }
1703
1704 /// ParseDirectiveEndIf
1705 /// ::= .endif
1706 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1707   if (getLexer().isNot(AsmToken::EndOfStatement))
1708     return TokError("unexpected token in '.endif' directive");
1709   
1710   Lex();
1711
1712   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1713       TheCondStack.empty())
1714     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1715                         ".else");
1716   if (!TheCondStack.empty()) {
1717     TheCondState = TheCondStack.back();
1718     TheCondStack.pop_back();
1719   }
1720
1721   return false;
1722 }
1723
1724 /// ParseDirectiveFile
1725 /// ::= .file [number] string
1726 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1727   // FIXME: I'm not sure what this is.
1728   int64_t FileNumber = -1;
1729   if (getLexer().is(AsmToken::Integer)) {
1730     FileNumber = getTok().getIntVal();
1731     Lex();
1732
1733     if (FileNumber < 1)
1734       return TokError("file number less than one");
1735   }
1736
1737   if (getLexer().isNot(AsmToken::String))
1738     return TokError("unexpected token in '.file' directive");
1739
1740   StringRef Filename = getTok().getString();
1741   Filename = Filename.substr(1, Filename.size()-2);
1742   Lex();
1743
1744   if (getLexer().isNot(AsmToken::EndOfStatement))
1745     return TokError("unexpected token in '.file' directive");
1746
1747   if (FileNumber == -1)
1748     getStreamer().EmitFileDirective(Filename);
1749   else
1750     getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1751
1752   return false;
1753 }
1754
1755 /// ParseDirectiveLine
1756 /// ::= .line [number]
1757 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1758   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1759     if (getLexer().isNot(AsmToken::Integer))
1760       return TokError("unexpected token in '.line' directive");
1761
1762     int64_t LineNumber = getTok().getIntVal();
1763     (void) LineNumber;
1764     Lex();
1765
1766     // FIXME: Do something with the .line.
1767   }
1768
1769   if (getLexer().isNot(AsmToken::EndOfStatement))
1770     return TokError("unexpected token in '.line' directive");
1771
1772   return false;
1773 }
1774
1775
1776 /// ParseDirectiveLoc
1777 /// ::= .loc number [number [number]]
1778 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1779   if (getLexer().isNot(AsmToken::Integer))
1780     return TokError("unexpected token in '.loc' directive");
1781
1782   // FIXME: What are these fields?
1783   int64_t FileNumber = getTok().getIntVal();
1784   (void) FileNumber;
1785   // FIXME: Validate file.
1786
1787   Lex();
1788   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1789     if (getLexer().isNot(AsmToken::Integer))
1790       return TokError("unexpected token in '.loc' directive");
1791
1792     int64_t Param2 = getTok().getIntVal();
1793     (void) Param2;
1794     Lex();
1795
1796     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1797       if (getLexer().isNot(AsmToken::Integer))
1798         return TokError("unexpected token in '.loc' directive");
1799
1800       int64_t Param3 = getTok().getIntVal();
1801       (void) Param3;
1802       Lex();
1803
1804       // FIXME: Do something with the .loc.
1805     }
1806   }
1807
1808   if (getLexer().isNot(AsmToken::EndOfStatement))
1809     return TokError("unexpected token in '.file' directive");
1810
1811   return false;
1812 }
1813
1814 /// ParseDirectiveMacrosOnOff
1815 /// ::= .macros_on
1816 /// ::= .macros_off
1817 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1818                                                  SMLoc DirectiveLoc) {
1819   if (getLexer().isNot(AsmToken::EndOfStatement))
1820     return Error(getLexer().getLoc(),
1821                  "unexpected token in '" + Directive + "' directive");
1822
1823   getParser().MacrosEnabled = Directive == ".macros_on";
1824
1825   return false;
1826 }
1827
1828 /// ParseDirectiveMacro
1829 /// ::= .macro name
1830 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1831                                            SMLoc DirectiveLoc) {
1832   StringRef Name;
1833   if (getParser().ParseIdentifier(Name))
1834     return TokError("expected identifier in directive");
1835
1836   if (getLexer().isNot(AsmToken::EndOfStatement))
1837     return TokError("unexpected token in '.macro' directive");
1838
1839   // Eat the end of statement.
1840   Lex();
1841
1842   AsmToken EndToken, StartToken = getTok();
1843
1844   // Lex the macro definition.
1845   for (;;) {
1846     // Check whether we have reached the end of the file.
1847     if (getLexer().is(AsmToken::Eof))
1848       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1849
1850     // Otherwise, check whether we have reach the .endmacro.
1851     if (getLexer().is(AsmToken::Identifier) &&
1852         (getTok().getIdentifier() == ".endm" ||
1853          getTok().getIdentifier() == ".endmacro")) {
1854       EndToken = getTok();
1855       Lex();
1856       if (getLexer().isNot(AsmToken::EndOfStatement))
1857         return TokError("unexpected token in '" + EndToken.getIdentifier() +
1858                         "' directive");
1859       break;
1860     }
1861
1862     // Otherwise, scan til the end of the statement.
1863     getParser().EatToEndOfStatement();
1864   }
1865
1866   if (getParser().MacroMap.lookup(Name)) {
1867     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1868   }
1869
1870   const char *BodyStart = StartToken.getLoc().getPointer();
1871   const char *BodyEnd = EndToken.getLoc().getPointer();
1872   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1873   getParser().MacroMap[Name] = new Macro(Name, Body);
1874   return false;
1875 }
1876
1877 /// ParseDirectiveEndMacro
1878 /// ::= .endm
1879 /// ::= .endmacro
1880 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1881                                            SMLoc DirectiveLoc) {
1882   if (getLexer().isNot(AsmToken::EndOfStatement))
1883     return TokError("unexpected token in '" + Directive + "' directive");
1884
1885   // If we are inside a macro instantiation, terminate the current
1886   // instantiation.
1887   if (!getParser().ActiveMacros.empty()) {
1888     getParser().HandleMacroExit();
1889     return false;
1890   }
1891
1892   // Otherwise, this .endmacro is a stray entry in the file; well formed
1893   // .endmacro directives are handled during the macro definition parsing.
1894   return TokError("unexpected '" + Directive + "' in file, "
1895                   "no current macro definition");
1896 }
1897
1898 /// \brief Create an MCAsmParser instance.
1899 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1900                                      MCContext &C, MCStreamer &Out,
1901                                      const MCAsmInfo &MAI) {
1902   return new AsmParser(T, SM, C, Out, MAI);
1903 }