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