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