OSDN Git Service

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