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