MC/AsmParser: Move Darwin specific parse to DarwinAsmParser.cpp.
[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/MC/MCParser/AsmParser.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCSectionELF.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetAsmParser.h"
30 using namespace llvm;
31
32 namespace {
33
34 /// \brief Generic implementations of directive handling, etc. which is shared
35 /// (or the default, at least) for all assembler parser.
36 class GenericAsmParser : public MCAsmParserExtension {
37 public:
38   GenericAsmParser() {}
39
40   virtual void Initialize(MCAsmParser &Parser) {
41     // Call the base implementation.
42     this->MCAsmParserExtension::Initialize(Parser);
43
44     // Debugging directives.
45     Parser.AddDirectiveHandler(this, ".file", MCAsmParser::DirectiveHandler(
46                                  &GenericAsmParser::ParseDirectiveFile));
47     Parser.AddDirectiveHandler(this, ".line", MCAsmParser::DirectiveHandler(
48                                  &GenericAsmParser::ParseDirectiveLine));
49     Parser.AddDirectiveHandler(this, ".loc", MCAsmParser::DirectiveHandler(
50                                  &GenericAsmParser::ParseDirectiveLoc));
51   }
52
53   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc); // ".file"
54   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc); // ".line"
55   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc); // ".loc"
56 };
57
58 class ELFAsmParser : public MCAsmParserExtension {
59   bool ParseSectionSwitch(StringRef Section, unsigned Type,
60                           unsigned Flags, SectionKind Kind);
61
62 public:
63   ELFAsmParser() {}
64
65   virtual void Initialize(MCAsmParser &Parser) {
66     // Call the base implementation.
67     this->MCAsmParserExtension::Initialize(Parser);
68
69     Parser.AddDirectiveHandler(this, ".data", MCAsmParser::DirectiveHandler(
70                                  &ELFAsmParser::ParseSectionDirectiveData));
71     Parser.AddDirectiveHandler(this, ".text", MCAsmParser::DirectiveHandler(
72                                  &ELFAsmParser::ParseSectionDirectiveText));
73   }
74
75   bool ParseSectionDirectiveData(StringRef, SMLoc) {
76     return ParseSectionSwitch(".data", MCSectionELF::SHT_PROGBITS,
77                               MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
78                               SectionKind::getDataRel());
79   }
80   bool ParseSectionDirectiveText(StringRef, SMLoc) {
81     return ParseSectionSwitch(".text", MCSectionELF::SHT_PROGBITS,
82                               MCSectionELF::SHF_EXECINSTR |
83                               MCSectionELF::SHF_ALLOC, SectionKind::getText());
84   }
85 };
86
87 }
88
89 namespace llvm {
90
91 extern MCAsmParserExtension *createDarwinAsmParser();
92
93 }
94
95 enum { DEFAULT_ADDRSPACE = 0 };
96
97 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
98                      MCStreamer &_Out, const MCAsmInfo &_MAI)
99   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
100     GenericParser(new GenericAsmParser), PlatformParser(0),
101     TargetParser(0), CurBuffer(0) {
102   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
103
104   // Initialize the generic parser.
105   GenericParser->Initialize(*this);
106
107   // Initialize the platform / file format parser.
108   //
109   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
110   // created.
111   if (_MAI.hasSubsectionsViaSymbols()) {
112     PlatformParser = createDarwinAsmParser();
113     PlatformParser->Initialize(*this);
114   } else {
115     PlatformParser = new ELFAsmParser;
116     PlatformParser->Initialize(*this);
117   }
118 }
119
120 AsmParser::~AsmParser() {
121   delete PlatformParser;
122   delete GenericParser;
123 }
124
125 void AsmParser::setTargetParser(TargetAsmParser &P) {
126   assert(!TargetParser && "Target parser is already initialized!");
127   TargetParser = &P;
128   TargetParser->Initialize(*this);
129 }
130
131 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
132   PrintMessage(L, Msg.str(), "warning");
133 }
134
135 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
136   PrintMessage(L, Msg.str(), "error");
137   return true;
138 }
139
140 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg, 
141                              const char *Type) const {
142   SrcMgr.PrintMessage(Loc, Msg, Type);
143 }
144                   
145 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
146   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
147   if (NewBuf == -1)
148     return true;
149   
150   CurBuffer = NewBuf;
151   
152   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
153   
154   return false;
155 }
156                   
157 const AsmToken &AsmParser::Lex() {
158   const AsmToken *tok = &Lexer.Lex();
159   
160   if (tok->is(AsmToken::Eof)) {
161     // If this is the end of an included file, pop the parent file off the
162     // include stack.
163     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
164     if (ParentIncludeLoc != SMLoc()) {
165       CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
166       Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), 
167                       ParentIncludeLoc.getPointer());
168       tok = &Lexer.Lex();
169     }
170   }
171     
172   if (tok->is(AsmToken::Error))
173     PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
174   
175   return *tok;
176 }
177
178 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
179   // Create the initial section, if requested.
180   //
181   // FIXME: Target hook & command line option for initial section.
182   if (!NoInitialTextSection)
183     Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
184                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
185                                       0, SectionKind::getText()));
186
187   // Prime the lexer.
188   Lex();
189   
190   bool HadError = false;
191   
192   AsmCond StartingCondState = TheCondState;
193
194   // While we have input, parse each statement.
195   while (Lexer.isNot(AsmToken::Eof)) {
196     if (!ParseStatement()) continue;
197   
198     // We had an error, remember it and recover by skipping to the next line.
199     HadError = true;
200     EatToEndOfStatement();
201   }
202
203   if (TheCondState.TheCond != StartingCondState.TheCond ||
204       TheCondState.Ignore != StartingCondState.Ignore)
205     return TokError("unmatched .ifs or .elses");
206   
207   // Finalize the output stream if there are no errors and if the client wants
208   // us to.
209   if (!HadError && !NoFinalize)  
210     Out.Finish();
211
212   return HadError;
213 }
214
215 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
216 void AsmParser::EatToEndOfStatement() {
217   while (Lexer.isNot(AsmToken::EndOfStatement) &&
218          Lexer.isNot(AsmToken::Eof))
219     Lex();
220   
221   // Eat EOL.
222   if (Lexer.is(AsmToken::EndOfStatement))
223     Lex();
224 }
225
226
227 /// ParseParenExpr - Parse a paren expression and return it.
228 /// NOTE: This assumes the leading '(' has already been consumed.
229 ///
230 /// parenexpr ::= expr)
231 ///
232 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
233   if (ParseExpression(Res)) return true;
234   if (Lexer.isNot(AsmToken::RParen))
235     return TokError("expected ')' in parentheses expression");
236   EndLoc = Lexer.getLoc();
237   Lex();
238   return false;
239 }
240
241 /// ParsePrimaryExpr - Parse a primary expression and return it.
242 ///  primaryexpr ::= (parenexpr
243 ///  primaryexpr ::= symbol
244 ///  primaryexpr ::= number
245 ///  primaryexpr ::= '.'
246 ///  primaryexpr ::= ~,+,- primaryexpr
247 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
248   switch (Lexer.getKind()) {
249   default:
250     return TokError("unknown token in expression");
251   case AsmToken::Exclaim:
252     Lex(); // Eat the operator.
253     if (ParsePrimaryExpr(Res, EndLoc))
254       return true;
255     Res = MCUnaryExpr::CreateLNot(Res, getContext());
256     return false;
257   case AsmToken::String:
258   case AsmToken::Identifier: {
259     // This is a symbol reference.
260     std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
261     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
262
263     // Mark the symbol as used in an expression.
264     Sym->setUsedInExpr(true);
265
266     // Lookup the symbol variant if used.
267     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
268     if (Split.first.size() != getTok().getIdentifier().size())
269       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
270
271     EndLoc = Lexer.getLoc();
272     Lex(); // Eat identifier.
273
274     // If this is an absolute variable reference, substitute it now to preserve
275     // semantics in the face of reassignment.
276     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
277       if (Variant)
278         return Error(EndLoc, "unexpected modified on variable reference");
279
280       Res = Sym->getVariableValue();
281       return false;
282     }
283
284     // Otherwise create a symbol ref.
285     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
286     return false;
287   }
288   case AsmToken::Integer: {
289     SMLoc Loc = getTok().getLoc();
290     int64_t IntVal = getTok().getIntVal();
291     Res = MCConstantExpr::Create(IntVal, getContext());
292     EndLoc = Lexer.getLoc();
293     Lex(); // Eat token.
294     // Look for 'b' or 'f' following an Integer as a directional label
295     if (Lexer.getKind() == AsmToken::Identifier) {
296       StringRef IDVal = getTok().getString();
297       if (IDVal == "f" || IDVal == "b"){
298         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
299                                                       IDVal == "f" ? 1 : 0);
300         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
301                                       getContext());
302         if(IDVal == "b" && Sym->isUndefined())
303           return Error(Loc, "invalid reference to undefined symbol");
304         EndLoc = Lexer.getLoc();
305         Lex(); // Eat identifier.
306       }
307     }
308     return false;
309   }
310   case AsmToken::Dot: {
311     // This is a '.' reference, which references the current PC.  Emit a
312     // temporary label to the streamer and refer to it.
313     MCSymbol *Sym = Ctx.CreateTempSymbol();
314     Out.EmitLabel(Sym);
315     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
316     EndLoc = Lexer.getLoc();
317     Lex(); // Eat identifier.
318     return false;
319   }
320       
321   case AsmToken::LParen:
322     Lex(); // Eat the '('.
323     return ParseParenExpr(Res, EndLoc);
324   case AsmToken::Minus:
325     Lex(); // Eat the operator.
326     if (ParsePrimaryExpr(Res, EndLoc))
327       return true;
328     Res = MCUnaryExpr::CreateMinus(Res, getContext());
329     return false;
330   case AsmToken::Plus:
331     Lex(); // Eat the operator.
332     if (ParsePrimaryExpr(Res, EndLoc))
333       return true;
334     Res = MCUnaryExpr::CreatePlus(Res, getContext());
335     return false;
336   case AsmToken::Tilde:
337     Lex(); // Eat the operator.
338     if (ParsePrimaryExpr(Res, EndLoc))
339       return true;
340     Res = MCUnaryExpr::CreateNot(Res, getContext());
341     return false;
342   }
343 }
344
345 bool AsmParser::ParseExpression(const MCExpr *&Res) {
346   SMLoc EndLoc;
347   return ParseExpression(Res, EndLoc);
348 }
349
350 /// ParseExpression - Parse an expression and return it.
351 /// 
352 ///  expr ::= expr +,- expr          -> lowest.
353 ///  expr ::= expr |,^,&,! expr      -> middle.
354 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
355 ///  expr ::= primaryexpr
356 ///
357 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
358   // Parse the expression.
359   Res = 0;
360   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
361     return true;
362
363   // Try to constant fold it up front, if possible.
364   int64_t Value;
365   if (Res->EvaluateAsAbsolute(Value))
366     Res = MCConstantExpr::Create(Value, getContext());
367
368   return false;
369 }
370
371 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
372   Res = 0;
373   return ParseParenExpr(Res, EndLoc) ||
374          ParseBinOpRHS(1, Res, EndLoc);
375 }
376
377 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
378   const MCExpr *Expr;
379   
380   SMLoc StartLoc = Lexer.getLoc();
381   if (ParseExpression(Expr))
382     return true;
383
384   if (!Expr->EvaluateAsAbsolute(Res))
385     return Error(StartLoc, "expected absolute expression");
386
387   return false;
388 }
389
390 static unsigned getBinOpPrecedence(AsmToken::TokenKind K, 
391                                    MCBinaryExpr::Opcode &Kind) {
392   switch (K) {
393   default:
394     return 0;    // not a binop.
395
396     // Lowest Precedence: &&, ||
397   case AsmToken::AmpAmp:
398     Kind = MCBinaryExpr::LAnd;
399     return 1;
400   case AsmToken::PipePipe:
401     Kind = MCBinaryExpr::LOr;
402     return 1;
403
404     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
405   case AsmToken::Plus:
406     Kind = MCBinaryExpr::Add;
407     return 2;
408   case AsmToken::Minus:
409     Kind = MCBinaryExpr::Sub;
410     return 2;
411   case AsmToken::EqualEqual:
412     Kind = MCBinaryExpr::EQ;
413     return 2;
414   case AsmToken::ExclaimEqual:
415   case AsmToken::LessGreater:
416     Kind = MCBinaryExpr::NE;
417     return 2;
418   case AsmToken::Less:
419     Kind = MCBinaryExpr::LT;
420     return 2;
421   case AsmToken::LessEqual:
422     Kind = MCBinaryExpr::LTE;
423     return 2;
424   case AsmToken::Greater:
425     Kind = MCBinaryExpr::GT;
426     return 2;
427   case AsmToken::GreaterEqual:
428     Kind = MCBinaryExpr::GTE;
429     return 2;
430
431     // Intermediate Precedence: |, &, ^
432     //
433     // FIXME: gas seems to support '!' as an infix operator?
434   case AsmToken::Pipe:
435     Kind = MCBinaryExpr::Or;
436     return 3;
437   case AsmToken::Caret:
438     Kind = MCBinaryExpr::Xor;
439     return 3;
440   case AsmToken::Amp:
441     Kind = MCBinaryExpr::And;
442     return 3;
443
444     // Highest Precedence: *, /, %, <<, >>
445   case AsmToken::Star:
446     Kind = MCBinaryExpr::Mul;
447     return 4;
448   case AsmToken::Slash:
449     Kind = MCBinaryExpr::Div;
450     return 4;
451   case AsmToken::Percent:
452     Kind = MCBinaryExpr::Mod;
453     return 4;
454   case AsmToken::LessLess:
455     Kind = MCBinaryExpr::Shl;
456     return 4;
457   case AsmToken::GreaterGreater:
458     Kind = MCBinaryExpr::Shr;
459     return 4;
460   }
461 }
462
463
464 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
465 /// Res contains the LHS of the expression on input.
466 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
467                               SMLoc &EndLoc) {
468   while (1) {
469     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
470     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
471     
472     // If the next token is lower precedence than we are allowed to eat, return
473     // successfully with what we ate already.
474     if (TokPrec < Precedence)
475       return false;
476     
477     Lex();
478     
479     // Eat the next primary expression.
480     const MCExpr *RHS;
481     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
482     
483     // If BinOp binds less tightly with RHS than the operator after RHS, let
484     // the pending operator take RHS as its LHS.
485     MCBinaryExpr::Opcode Dummy;
486     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
487     if (TokPrec < NextTokPrec) {
488       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
489     }
490
491     // Merge LHS and RHS according to operator.
492     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
493   }
494 }
495
496   
497   
498   
499 /// ParseStatement:
500 ///   ::= EndOfStatement
501 ///   ::= Label* Directive ...Operands... EndOfStatement
502 ///   ::= Label* Identifier OperandList* EndOfStatement
503 bool AsmParser::ParseStatement() {
504   if (Lexer.is(AsmToken::EndOfStatement)) {
505     Out.AddBlankLine();
506     Lex();
507     return false;
508   }
509
510   // Statements always start with an identifier.
511   AsmToken ID = getTok();
512   SMLoc IDLoc = ID.getLoc();
513   StringRef IDVal;
514   int64_t LocalLabelVal = -1;
515   // GUESS allow an integer followed by a ':' as a directional local label
516   if (Lexer.is(AsmToken::Integer)) {
517     LocalLabelVal = getTok().getIntVal();
518     if (LocalLabelVal < 0) {
519       if (!TheCondState.Ignore)
520         return TokError("unexpected token at start of statement");
521       IDVal = "";
522     }
523     else {
524       IDVal = getTok().getString();
525       Lex(); // Consume the integer token to be used as an identifier token.
526       if (Lexer.getKind() != AsmToken::Colon) {
527         if (!TheCondState.Ignore)
528           return TokError("unexpected token at start of statement");
529       }
530     }
531   }
532   else if (ParseIdentifier(IDVal)) {
533     if (!TheCondState.Ignore)
534       return TokError("unexpected token at start of statement");
535     IDVal = "";
536   }
537
538   // Handle conditional assembly here before checking for skipping.  We
539   // have to do this so that .endif isn't skipped in a ".if 0" block for
540   // example.
541   if (IDVal == ".if")
542     return ParseDirectiveIf(IDLoc);
543   if (IDVal == ".elseif")
544     return ParseDirectiveElseIf(IDLoc);
545   if (IDVal == ".else")
546     return ParseDirectiveElse(IDLoc);
547   if (IDVal == ".endif")
548     return ParseDirectiveEndIf(IDLoc);
549     
550   // If we are in a ".if 0" block, ignore this statement.
551   if (TheCondState.Ignore) {
552     EatToEndOfStatement();
553     return false;
554   }
555   
556   // FIXME: Recurse on local labels?
557
558   // See what kind of statement we have.
559   switch (Lexer.getKind()) {
560   case AsmToken::Colon: {
561     // identifier ':'   -> Label.
562     Lex();
563
564     // Diagnose attempt to use a variable as a label.
565     //
566     // FIXME: Diagnostics. Note the location of the definition as a label.
567     // FIXME: This doesn't diagnose assignment to a symbol which has been
568     // implicitly marked as external.
569     MCSymbol *Sym;
570     if (LocalLabelVal == -1)
571       Sym = getContext().GetOrCreateSymbol(IDVal);
572     else
573       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
574     if (!Sym->isUndefined() || Sym->isVariable())
575       return Error(IDLoc, "invalid symbol redefinition");
576     
577     // Emit the label.
578     Out.EmitLabel(Sym);
579    
580     // Consume any end of statement token, if present, to avoid spurious
581     // AddBlankLine calls().
582     if (Lexer.is(AsmToken::EndOfStatement)) {
583       Lex();
584       if (Lexer.is(AsmToken::Eof))
585         return false;
586     }
587
588     return ParseStatement();
589   }
590
591   case AsmToken::Equal:
592     // identifier '=' ... -> assignment statement
593     Lex();
594
595     return ParseAssignment(IDVal);
596
597   default: // Normal instruction or directive.
598     break;
599   }
600   
601   // Otherwise, we have a normal instruction or directive.  
602   if (IDVal[0] == '.') {
603     // Assembler features
604     if (IDVal == ".set")
605       return ParseDirectiveSet();
606
607     // Data directives
608
609     if (IDVal == ".ascii")
610       return ParseDirectiveAscii(false);
611     if (IDVal == ".asciz")
612       return ParseDirectiveAscii(true);
613
614     if (IDVal == ".byte")
615       return ParseDirectiveValue(1);
616     if (IDVal == ".short")
617       return ParseDirectiveValue(2);
618     if (IDVal == ".long")
619       return ParseDirectiveValue(4);
620     if (IDVal == ".quad")
621       return ParseDirectiveValue(8);
622
623     // FIXME: Target hooks for IsPow2.
624     if (IDVal == ".align")
625       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
626     if (IDVal == ".align32")
627       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
628     if (IDVal == ".balign")
629       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
630     if (IDVal == ".balignw")
631       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
632     if (IDVal == ".balignl")
633       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
634     if (IDVal == ".p2align")
635       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
636     if (IDVal == ".p2alignw")
637       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
638     if (IDVal == ".p2alignl")
639       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
640
641     if (IDVal == ".org")
642       return ParseDirectiveOrg();
643
644     if (IDVal == ".fill")
645       return ParseDirectiveFill();
646     if (IDVal == ".space")
647       return ParseDirectiveSpace();
648
649     // Symbol attribute directives
650
651     if (IDVal == ".globl" || IDVal == ".global")
652       return ParseDirectiveSymbolAttribute(MCSA_Global);
653     if (IDVal == ".hidden")
654       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
655     if (IDVal == ".indirect_symbol")
656       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
657     if (IDVal == ".internal")
658       return ParseDirectiveSymbolAttribute(MCSA_Internal);
659     if (IDVal == ".lazy_reference")
660       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
661     if (IDVal == ".no_dead_strip")
662       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
663     if (IDVal == ".private_extern")
664       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
665     if (IDVal == ".protected")
666       return ParseDirectiveSymbolAttribute(MCSA_Protected);
667     if (IDVal == ".reference")
668       return ParseDirectiveSymbolAttribute(MCSA_Reference);
669     if (IDVal == ".type")
670       return ParseDirectiveELFType();
671     if (IDVal == ".weak")
672       return ParseDirectiveSymbolAttribute(MCSA_Weak);
673     if (IDVal == ".weak_definition")
674       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
675     if (IDVal == ".weak_reference")
676       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
677     if (IDVal == ".weak_def_can_be_hidden")
678       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
679
680     if (IDVal == ".comm")
681       return ParseDirectiveComm(/*IsLocal=*/false);
682     if (IDVal == ".lcomm")
683       return ParseDirectiveComm(/*IsLocal=*/true);
684
685     if (IDVal == ".abort")
686       return ParseDirectiveAbort();
687     if (IDVal == ".include")
688       return ParseDirectiveInclude();
689
690     // Look up the handler in the handler table.
691     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
692       DirectiveMap.lookup(IDVal);
693     if (Handler.first)
694       return (Handler.first->*Handler.second)(IDVal, IDLoc);
695
696     // Target hook for parsing target specific directives.
697     if (!getTargetParser().ParseDirective(ID))
698       return false;
699
700     Warning(IDLoc, "ignoring directive for now");
701     EatToEndOfStatement();
702     return false;
703   }
704
705   // Canonicalize the opcode to lower case.
706   SmallString<128> Opcode;
707   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
708     Opcode.push_back(tolower(IDVal[i]));
709   
710   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
711   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
712                                                      ParsedOperands);
713   if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
714     HadError = TokError("unexpected token in argument list");
715
716   // If parsing succeeded, match the instruction.
717   if (!HadError) {
718     MCInst Inst;
719     if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
720       // Emit the instruction on success.
721       Out.EmitInstruction(Inst);
722     } else {
723       // Otherwise emit a diagnostic about the match failure and set the error
724       // flag.
725       //
726       // FIXME: We should give nicer diagnostics about the exact failure.
727       Error(IDLoc, "unrecognized instruction");
728       HadError = true;
729     }
730   }
731
732   // If there was no error, consume the end-of-statement token. Otherwise this
733   // will be done by our caller.
734   if (!HadError)
735     Lex();
736
737   // Free any parsed operands.
738   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
739     delete ParsedOperands[i];
740
741   return HadError;
742 }
743
744 bool AsmParser::ParseAssignment(const StringRef &Name) {
745   // FIXME: Use better location, we should use proper tokens.
746   SMLoc EqualLoc = Lexer.getLoc();
747
748   const MCExpr *Value;
749   if (ParseExpression(Value))
750     return true;
751   
752   if (Lexer.isNot(AsmToken::EndOfStatement))
753     return TokError("unexpected token in assignment");
754
755   // Eat the end of statement marker.
756   Lex();
757
758   // Validate that the LHS is allowed to be a variable (either it has not been
759   // used as a symbol, or it is an absolute symbol).
760   MCSymbol *Sym = getContext().LookupSymbol(Name);
761   if (Sym) {
762     // Diagnose assignment to a label.
763     //
764     // FIXME: Diagnostics. Note the location of the definition as a label.
765     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
766     if (Sym->isUndefined() && !Sym->isUsedInExpr())
767       ; // Allow redefinitions of undefined symbols only used in directives.
768     else if (!Sym->isUndefined() && !Sym->isAbsolute())
769       return Error(EqualLoc, "redefinition of '" + Name + "'");
770     else if (!Sym->isVariable())
771       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
772     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
773       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
774                    Name + "'");
775   } else
776     Sym = getContext().GetOrCreateSymbol(Name);
777
778   // FIXME: Handle '.'.
779
780   Sym->setUsedInExpr(true);
781
782   // Do the assignment.
783   Out.EmitAssignment(Sym, Value);
784
785   return false;
786 }
787
788 /// ParseIdentifier:
789 ///   ::= identifier
790 ///   ::= string
791 bool AsmParser::ParseIdentifier(StringRef &Res) {
792   if (Lexer.isNot(AsmToken::Identifier) &&
793       Lexer.isNot(AsmToken::String))
794     return true;
795
796   Res = getTok().getIdentifier();
797
798   Lex(); // Consume the identifier token.
799
800   return false;
801 }
802
803 /// ParseDirectiveSet:
804 ///   ::= .set identifier ',' expression
805 bool AsmParser::ParseDirectiveSet() {
806   StringRef Name;
807
808   if (ParseIdentifier(Name))
809     return TokError("expected identifier after '.set' directive");
810   
811   if (getLexer().isNot(AsmToken::Comma))
812     return TokError("unexpected token in '.set'");
813   Lex();
814
815   return ParseAssignment(Name);
816 }
817
818 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
819                                       unsigned Flags, SectionKind Kind) {
820   if (getLexer().isNot(AsmToken::EndOfStatement))
821     return TokError("unexpected token in section switching directive");
822   Lex();
823
824   getStreamer().SwitchSection(getContext().getELFSection(
825                                 Section, Type, Flags, Kind));
826
827   return false;
828 }
829
830 bool AsmParser::ParseEscapedString(std::string &Data) {
831   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
832
833   Data = "";
834   StringRef Str = getTok().getStringContents();
835   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
836     if (Str[i] != '\\') {
837       Data += Str[i];
838       continue;
839     }
840
841     // Recognize escaped characters. Note that this escape semantics currently
842     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
843     ++i;
844     if (i == e)
845       return TokError("unexpected backslash at end of string");
846
847     // Recognize octal sequences.
848     if ((unsigned) (Str[i] - '0') <= 7) {
849       // Consume up to three octal characters.
850       unsigned Value = Str[i] - '0';
851
852       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
853         ++i;
854         Value = Value * 8 + (Str[i] - '0');
855
856         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
857           ++i;
858           Value = Value * 8 + (Str[i] - '0');
859         }
860       }
861
862       if (Value > 255)
863         return TokError("invalid octal escape sequence (out of range)");
864
865       Data += (unsigned char) Value;
866       continue;
867     }
868
869     // Otherwise recognize individual escapes.
870     switch (Str[i]) {
871     default:
872       // Just reject invalid escape sequences for now.
873       return TokError("invalid escape sequence (unrecognized character)");
874
875     case 'b': Data += '\b'; break;
876     case 'f': Data += '\f'; break;
877     case 'n': Data += '\n'; break;
878     case 'r': Data += '\r'; break;
879     case 't': Data += '\t'; break;
880     case '"': Data += '"'; break;
881     case '\\': Data += '\\'; break;
882     }
883   }
884
885   return false;
886 }
887
888 /// ParseDirectiveAscii:
889 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
890 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
891   if (getLexer().isNot(AsmToken::EndOfStatement)) {
892     for (;;) {
893       if (getLexer().isNot(AsmToken::String))
894         return TokError("expected string in '.ascii' or '.asciz' directive");
895
896       std::string Data;
897       if (ParseEscapedString(Data))
898         return true;
899
900       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
901       if (ZeroTerminated)
902         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
903
904       Lex();
905
906       if (getLexer().is(AsmToken::EndOfStatement))
907         break;
908
909       if (getLexer().isNot(AsmToken::Comma))
910         return TokError("unexpected token in '.ascii' or '.asciz' directive");
911       Lex();
912     }
913   }
914
915   Lex();
916   return false;
917 }
918
919 /// ParseDirectiveValue
920 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
921 bool AsmParser::ParseDirectiveValue(unsigned Size) {
922   if (getLexer().isNot(AsmToken::EndOfStatement)) {
923     for (;;) {
924       const MCExpr *Value;
925       SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
926       if (ParseExpression(Value))
927         return true;
928
929       // Special case constant expressions to match code generator.
930       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
931         getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
932       else
933         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
934
935       if (getLexer().is(AsmToken::EndOfStatement))
936         break;
937       
938       // FIXME: Improve diagnostic.
939       if (getLexer().isNot(AsmToken::Comma))
940         return TokError("unexpected token in directive");
941       Lex();
942     }
943   }
944
945   Lex();
946   return false;
947 }
948
949 /// ParseDirectiveSpace
950 ///  ::= .space expression [ , expression ]
951 bool AsmParser::ParseDirectiveSpace() {
952   int64_t NumBytes;
953   if (ParseAbsoluteExpression(NumBytes))
954     return true;
955
956   int64_t FillExpr = 0;
957   if (getLexer().isNot(AsmToken::EndOfStatement)) {
958     if (getLexer().isNot(AsmToken::Comma))
959       return TokError("unexpected token in '.space' directive");
960     Lex();
961     
962     if (ParseAbsoluteExpression(FillExpr))
963       return true;
964
965     if (getLexer().isNot(AsmToken::EndOfStatement))
966       return TokError("unexpected token in '.space' directive");
967   }
968
969   Lex();
970
971   if (NumBytes <= 0)
972     return TokError("invalid number of bytes in '.space' directive");
973
974   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
975   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
976
977   return false;
978 }
979
980 /// ParseDirectiveFill
981 ///  ::= .fill expression , expression , expression
982 bool AsmParser::ParseDirectiveFill() {
983   int64_t NumValues;
984   if (ParseAbsoluteExpression(NumValues))
985     return true;
986
987   if (getLexer().isNot(AsmToken::Comma))
988     return TokError("unexpected token in '.fill' directive");
989   Lex();
990   
991   int64_t FillSize;
992   if (ParseAbsoluteExpression(FillSize))
993     return true;
994
995   if (getLexer().isNot(AsmToken::Comma))
996     return TokError("unexpected token in '.fill' directive");
997   Lex();
998   
999   int64_t FillExpr;
1000   if (ParseAbsoluteExpression(FillExpr))
1001     return true;
1002
1003   if (getLexer().isNot(AsmToken::EndOfStatement))
1004     return TokError("unexpected token in '.fill' directive");
1005   
1006   Lex();
1007
1008   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1009     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1010
1011   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1012     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1013
1014   return false;
1015 }
1016
1017 /// ParseDirectiveOrg
1018 ///  ::= .org expression [ , expression ]
1019 bool AsmParser::ParseDirectiveOrg() {
1020   const MCExpr *Offset;
1021   if (ParseExpression(Offset))
1022     return true;
1023
1024   // Parse optional fill expression.
1025   int64_t FillExpr = 0;
1026   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1027     if (getLexer().isNot(AsmToken::Comma))
1028       return TokError("unexpected token in '.org' directive");
1029     Lex();
1030     
1031     if (ParseAbsoluteExpression(FillExpr))
1032       return true;
1033
1034     if (getLexer().isNot(AsmToken::EndOfStatement))
1035       return TokError("unexpected token in '.org' directive");
1036   }
1037
1038   Lex();
1039
1040   // FIXME: Only limited forms of relocatable expressions are accepted here, it
1041   // has to be relative to the current section.
1042   getStreamer().EmitValueToOffset(Offset, FillExpr);
1043
1044   return false;
1045 }
1046
1047 /// ParseDirectiveAlign
1048 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
1049 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1050   SMLoc AlignmentLoc = getLexer().getLoc();
1051   int64_t Alignment;
1052   if (ParseAbsoluteExpression(Alignment))
1053     return true;
1054
1055   SMLoc MaxBytesLoc;
1056   bool HasFillExpr = false;
1057   int64_t FillExpr = 0;
1058   int64_t MaxBytesToFill = 0;
1059   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1060     if (getLexer().isNot(AsmToken::Comma))
1061       return TokError("unexpected token in directive");
1062     Lex();
1063
1064     // The fill expression can be omitted while specifying a maximum number of
1065     // alignment bytes, e.g:
1066     //  .align 3,,4
1067     if (getLexer().isNot(AsmToken::Comma)) {
1068       HasFillExpr = true;
1069       if (ParseAbsoluteExpression(FillExpr))
1070         return true;
1071     }
1072
1073     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1074       if (getLexer().isNot(AsmToken::Comma))
1075         return TokError("unexpected token in directive");
1076       Lex();
1077
1078       MaxBytesLoc = getLexer().getLoc();
1079       if (ParseAbsoluteExpression(MaxBytesToFill))
1080         return true;
1081       
1082       if (getLexer().isNot(AsmToken::EndOfStatement))
1083         return TokError("unexpected token in directive");
1084     }
1085   }
1086
1087   Lex();
1088
1089   if (!HasFillExpr)
1090     FillExpr = 0;
1091
1092   // Compute alignment in bytes.
1093   if (IsPow2) {
1094     // FIXME: Diagnose overflow.
1095     if (Alignment >= 32) {
1096       Error(AlignmentLoc, "invalid alignment value");
1097       Alignment = 31;
1098     }
1099
1100     Alignment = 1ULL << Alignment;
1101   }
1102
1103   // Diagnose non-sensical max bytes to align.
1104   if (MaxBytesLoc.isValid()) {
1105     if (MaxBytesToFill < 1) {
1106       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1107             "many bytes, ignoring maximum bytes expression");
1108       MaxBytesToFill = 0;
1109     }
1110
1111     if (MaxBytesToFill >= Alignment) {
1112       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1113               "has no effect");
1114       MaxBytesToFill = 0;
1115     }
1116   }
1117
1118   // Check whether we should use optimal code alignment for this .align
1119   // directive.
1120   //
1121   // FIXME: This should be using a target hook.
1122   bool UseCodeAlign = false;
1123   if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1124         getStreamer().getCurrentSection()))
1125       UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1126   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1127       ValueSize == 1 && UseCodeAlign) {
1128     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1129   } else {
1130     // FIXME: Target specific behavior about how the "extra" bytes are filled.
1131     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1132   }
1133
1134   return false;
1135 }
1136
1137 /// ParseDirectiveSymbolAttribute
1138 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1139 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1140   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1141     for (;;) {
1142       StringRef Name;
1143
1144       if (ParseIdentifier(Name))
1145         return TokError("expected identifier in directive");
1146       
1147       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1148
1149       getStreamer().EmitSymbolAttribute(Sym, Attr);
1150
1151       if (getLexer().is(AsmToken::EndOfStatement))
1152         break;
1153
1154       if (getLexer().isNot(AsmToken::Comma))
1155         return TokError("unexpected token in directive");
1156       Lex();
1157     }
1158   }
1159
1160   Lex();
1161   return false;  
1162 }
1163
1164 /// ParseDirectiveELFType
1165 ///  ::= .type identifier , @attribute
1166 bool AsmParser::ParseDirectiveELFType() {
1167   StringRef Name;
1168   if (ParseIdentifier(Name))
1169     return TokError("expected identifier in directive");
1170
1171   // Handle the identifier as the key symbol.
1172   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1173
1174   if (getLexer().isNot(AsmToken::Comma))
1175     return TokError("unexpected token in '.type' directive");
1176   Lex();
1177
1178   if (getLexer().isNot(AsmToken::At))
1179     return TokError("expected '@' before type");
1180   Lex();
1181
1182   StringRef Type;
1183   SMLoc TypeLoc;
1184
1185   TypeLoc = getLexer().getLoc();
1186   if (ParseIdentifier(Type))
1187     return TokError("expected symbol type in directive");
1188
1189   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1190     .Case("function", MCSA_ELF_TypeFunction)
1191     .Case("object", MCSA_ELF_TypeObject)
1192     .Case("tls_object", MCSA_ELF_TypeTLS)
1193     .Case("common", MCSA_ELF_TypeCommon)
1194     .Case("notype", MCSA_ELF_TypeNoType)
1195     .Default(MCSA_Invalid);
1196
1197   if (Attr == MCSA_Invalid)
1198     return Error(TypeLoc, "unsupported attribute in '.type' directive");
1199
1200   if (getLexer().isNot(AsmToken::EndOfStatement))
1201     return TokError("unexpected token in '.type' directive");
1202
1203   Lex();
1204
1205   getStreamer().EmitSymbolAttribute(Sym, Attr);
1206
1207   return false;
1208 }
1209
1210 /// ParseDirectiveComm
1211 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1212 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1213   SMLoc IDLoc = getLexer().getLoc();
1214   StringRef Name;
1215   if (ParseIdentifier(Name))
1216     return TokError("expected identifier in directive");
1217   
1218   // Handle the identifier as the key symbol.
1219   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1220
1221   if (getLexer().isNot(AsmToken::Comma))
1222     return TokError("unexpected token in directive");
1223   Lex();
1224
1225   int64_t Size;
1226   SMLoc SizeLoc = getLexer().getLoc();
1227   if (ParseAbsoluteExpression(Size))
1228     return true;
1229
1230   int64_t Pow2Alignment = 0;
1231   SMLoc Pow2AlignmentLoc;
1232   if (getLexer().is(AsmToken::Comma)) {
1233     Lex();
1234     Pow2AlignmentLoc = getLexer().getLoc();
1235     if (ParseAbsoluteExpression(Pow2Alignment))
1236       return true;
1237     
1238     // If this target takes alignments in bytes (not log) validate and convert.
1239     if (Lexer.getMAI().getAlignmentIsInBytes()) {
1240       if (!isPowerOf2_64(Pow2Alignment))
1241         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1242       Pow2Alignment = Log2_64(Pow2Alignment);
1243     }
1244   }
1245   
1246   if (getLexer().isNot(AsmToken::EndOfStatement))
1247     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1248   
1249   Lex();
1250
1251   // NOTE: a size of zero for a .comm should create a undefined symbol
1252   // but a size of .lcomm creates a bss symbol of size zero.
1253   if (Size < 0)
1254     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1255                  "be less than zero");
1256
1257   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1258   // may internally end up wanting an alignment in bytes.
1259   // FIXME: Diagnose overflow.
1260   if (Pow2Alignment < 0)
1261     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1262                  "alignment, can't be less than zero");
1263
1264   if (!Sym->isUndefined())
1265     return Error(IDLoc, "invalid symbol redefinition");
1266
1267   // '.lcomm' is equivalent to '.zerofill'.
1268   // Create the Symbol as a common or local common with Size and Pow2Alignment
1269   if (IsLocal) {
1270     getStreamer().EmitZerofill(Ctx.getMachOSection(
1271                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1272                                  0, SectionKind::getBSS()),
1273                                Sym, Size, 1 << Pow2Alignment);
1274     return false;
1275   }
1276
1277   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1278   return false;
1279 }
1280
1281 /// ParseDirectiveAbort
1282 ///  ::= .abort [ "abort_string" ]
1283 bool AsmParser::ParseDirectiveAbort() {
1284   // FIXME: Use loc from directive.
1285   SMLoc Loc = getLexer().getLoc();
1286
1287   StringRef Str = "";
1288   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1289     if (getLexer().isNot(AsmToken::String))
1290       return TokError("expected string in '.abort' directive");
1291     
1292     Str = getTok().getString();
1293
1294     Lex();
1295   }
1296
1297   if (getLexer().isNot(AsmToken::EndOfStatement))
1298     return TokError("unexpected token in '.abort' directive");
1299   
1300   Lex();
1301
1302   // FIXME: Handle here.
1303   if (Str.empty())
1304     Error(Loc, ".abort detected. Assembly stopping.");
1305   else
1306     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1307
1308   return false;
1309 }
1310
1311 /// ParseDirectiveInclude
1312 ///  ::= .include "filename"
1313 bool AsmParser::ParseDirectiveInclude() {
1314   if (getLexer().isNot(AsmToken::String))
1315     return TokError("expected string in '.include' directive");
1316   
1317   std::string Filename = getTok().getString();
1318   SMLoc IncludeLoc = getLexer().getLoc();
1319   Lex();
1320
1321   if (getLexer().isNot(AsmToken::EndOfStatement))
1322     return TokError("unexpected token in '.include' directive");
1323   
1324   // Strip the quotes.
1325   Filename = Filename.substr(1, Filename.size()-2);
1326   
1327   // Attempt to switch the lexer to the included file before consuming the end
1328   // of statement to avoid losing it when we switch.
1329   if (EnterIncludeFile(Filename)) {
1330     PrintMessage(IncludeLoc,
1331                  "Could not find include file '" + Filename + "'",
1332                  "error");
1333     return true;
1334   }
1335
1336   return false;
1337 }
1338
1339 /// ParseDirectiveIf
1340 /// ::= .if expression
1341 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1342   TheCondStack.push_back(TheCondState);
1343   TheCondState.TheCond = AsmCond::IfCond;
1344   if(TheCondState.Ignore) {
1345     EatToEndOfStatement();
1346   }
1347   else {
1348     int64_t ExprValue;
1349     if (ParseAbsoluteExpression(ExprValue))
1350       return true;
1351
1352     if (getLexer().isNot(AsmToken::EndOfStatement))
1353       return TokError("unexpected token in '.if' directive");
1354     
1355     Lex();
1356
1357     TheCondState.CondMet = ExprValue;
1358     TheCondState.Ignore = !TheCondState.CondMet;
1359   }
1360
1361   return false;
1362 }
1363
1364 /// ParseDirectiveElseIf
1365 /// ::= .elseif expression
1366 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1367   if (TheCondState.TheCond != AsmCond::IfCond &&
1368       TheCondState.TheCond != AsmCond::ElseIfCond)
1369       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1370                           " an .elseif");
1371   TheCondState.TheCond = AsmCond::ElseIfCond;
1372
1373   bool LastIgnoreState = false;
1374   if (!TheCondStack.empty())
1375       LastIgnoreState = TheCondStack.back().Ignore;
1376   if (LastIgnoreState || TheCondState.CondMet) {
1377     TheCondState.Ignore = true;
1378     EatToEndOfStatement();
1379   }
1380   else {
1381     int64_t ExprValue;
1382     if (ParseAbsoluteExpression(ExprValue))
1383       return true;
1384
1385     if (getLexer().isNot(AsmToken::EndOfStatement))
1386       return TokError("unexpected token in '.elseif' directive");
1387     
1388     Lex();
1389     TheCondState.CondMet = ExprValue;
1390     TheCondState.Ignore = !TheCondState.CondMet;
1391   }
1392
1393   return false;
1394 }
1395
1396 /// ParseDirectiveElse
1397 /// ::= .else
1398 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1399   if (getLexer().isNot(AsmToken::EndOfStatement))
1400     return TokError("unexpected token in '.else' directive");
1401   
1402   Lex();
1403
1404   if (TheCondState.TheCond != AsmCond::IfCond &&
1405       TheCondState.TheCond != AsmCond::ElseIfCond)
1406       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1407                           ".elseif");
1408   TheCondState.TheCond = AsmCond::ElseCond;
1409   bool LastIgnoreState = false;
1410   if (!TheCondStack.empty())
1411     LastIgnoreState = TheCondStack.back().Ignore;
1412   if (LastIgnoreState || TheCondState.CondMet)
1413     TheCondState.Ignore = true;
1414   else
1415     TheCondState.Ignore = false;
1416
1417   return false;
1418 }
1419
1420 /// ParseDirectiveEndIf
1421 /// ::= .endif
1422 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1423   if (getLexer().isNot(AsmToken::EndOfStatement))
1424     return TokError("unexpected token in '.endif' directive");
1425   
1426   Lex();
1427
1428   if ((TheCondState.TheCond == AsmCond::NoCond) ||
1429       TheCondStack.empty())
1430     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1431                         ".else");
1432   if (!TheCondStack.empty()) {
1433     TheCondState = TheCondStack.back();
1434     TheCondStack.pop_back();
1435   }
1436
1437   return false;
1438 }
1439
1440 /// ParseDirectiveFile
1441 /// ::= .file [number] string
1442 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1443   // FIXME: I'm not sure what this is.
1444   int64_t FileNumber = -1;
1445   if (getLexer().is(AsmToken::Integer)) {
1446     FileNumber = getTok().getIntVal();
1447     Lex();
1448
1449     if (FileNumber < 1)
1450       return TokError("file number less than one");
1451   }
1452
1453   if (getLexer().isNot(AsmToken::String))
1454     return TokError("unexpected token in '.file' directive");
1455
1456   StringRef Filename = getTok().getString();
1457   Filename = Filename.substr(1, Filename.size()-2);
1458   Lex();
1459
1460   if (getLexer().isNot(AsmToken::EndOfStatement))
1461     return TokError("unexpected token in '.file' directive");
1462
1463   if (FileNumber == -1)
1464     getStreamer().EmitFileDirective(Filename);
1465   else
1466     getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1467
1468   return false;
1469 }
1470
1471 /// ParseDirectiveLine
1472 /// ::= .line [number]
1473 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1474   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1475     if (getLexer().isNot(AsmToken::Integer))
1476       return TokError("unexpected token in '.line' directive");
1477
1478     int64_t LineNumber = getTok().getIntVal();
1479     (void) LineNumber;
1480     Lex();
1481
1482     // FIXME: Do something with the .line.
1483   }
1484
1485   if (getLexer().isNot(AsmToken::EndOfStatement))
1486     return TokError("unexpected token in '.line' directive");
1487
1488   return false;
1489 }
1490
1491
1492 /// ParseDirectiveLoc
1493 /// ::= .loc number [number [number]]
1494 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1495   if (getLexer().isNot(AsmToken::Integer))
1496     return TokError("unexpected token in '.loc' directive");
1497
1498   // FIXME: What are these fields?
1499   int64_t FileNumber = getTok().getIntVal();
1500   (void) FileNumber;
1501   // FIXME: Validate file.
1502
1503   Lex();
1504   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1505     if (getLexer().isNot(AsmToken::Integer))
1506       return TokError("unexpected token in '.loc' directive");
1507
1508     int64_t Param2 = getTok().getIntVal();
1509     (void) Param2;
1510     Lex();
1511
1512     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1513       if (getLexer().isNot(AsmToken::Integer))
1514         return TokError("unexpected token in '.loc' directive");
1515
1516       int64_t Param3 = getTok().getIntVal();
1517       (void) Param3;
1518       Lex();
1519
1520       // FIXME: Do something with the .loc.
1521     }
1522   }
1523
1524   if (getLexer().isNot(AsmToken::EndOfStatement))
1525     return TokError("unexpected token in '.file' directive");
1526
1527   return false;
1528 }
1529