Added llvm-mc support for parsing the .include directive.
[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 "AsmExpr.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
25 void AsmParser::Warning(SMLoc L, const char *Msg) {
26   Lexer.PrintMessage(L, Msg, "warning");
27 }
28
29 bool AsmParser::Error(SMLoc L, const char *Msg) {
30   Lexer.PrintMessage(L, Msg, "error");
31   return true;
32 }
33
34 bool AsmParser::TokError(const char *Msg) {
35   Lexer.PrintMessage(Lexer.getLoc(), Msg, "error");
36   return true;
37 }
38
39 bool AsmParser::Run() {
40   // Prime the lexer.
41   Lexer.Lex();
42   
43   bool HadError = false;
44   
45   // While we have input, parse each statement.
46   while (Lexer.isNot(asmtok::Eof)) {
47     if (!ParseStatement()) continue;
48   
49     // If we had an error, remember it and recover by skipping to the next line.
50     HadError = true;
51     EatToEndOfStatement();
52   }
53   
54   return HadError;
55 }
56
57 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
58 void AsmParser::EatToEndOfStatement() {
59   while (Lexer.isNot(asmtok::EndOfStatement) &&
60          Lexer.isNot(asmtok::Eof))
61     Lexer.Lex();
62   
63   // Eat EOL.
64   if (Lexer.is(asmtok::EndOfStatement))
65     Lexer.Lex();
66 }
67
68
69 /// ParseParenExpr - Parse a paren expression and return it.
70 /// NOTE: This assumes the leading '(' has already been consumed.
71 ///
72 /// parenexpr ::= expr)
73 ///
74 bool AsmParser::ParseParenExpr(AsmExpr *&Res) {
75   if (ParseExpression(Res)) return true;
76   if (Lexer.isNot(asmtok::RParen))
77     return TokError("expected ')' in parentheses expression");
78   Lexer.Lex();
79   return false;
80 }
81
82 /// ParsePrimaryExpr - Parse a primary expression and return it.
83 ///  primaryexpr ::= (parenexpr
84 ///  primaryexpr ::= symbol
85 ///  primaryexpr ::= number
86 ///  primaryexpr ::= ~,+,- primaryexpr
87 bool AsmParser::ParsePrimaryExpr(AsmExpr *&Res) {
88   switch (Lexer.getKind()) {
89   default:
90     return TokError("unknown token in expression");
91   case asmtok::Exclaim:
92     Lexer.Lex(); // Eat the operator.
93     if (ParsePrimaryExpr(Res))
94       return true;
95     Res = new AsmUnaryExpr(AsmUnaryExpr::LNot, Res);
96     return false;
97   case asmtok::Identifier: {
98     // This is a label, this should be parsed as part of an expression, to
99     // handle things like LFOO+4.
100     MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
101
102     // If this is use of an undefined symbol then mark it external.
103     if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
104       Sym->setExternal(true);
105     
106     Res = new AsmSymbolRefExpr(Sym);
107     Lexer.Lex(); // Eat identifier.
108     return false;
109   }
110   case asmtok::IntVal:
111     Res = new AsmConstantExpr(Lexer.getCurIntVal());
112     Lexer.Lex(); // Eat identifier.
113     return false;
114   case asmtok::LParen:
115     Lexer.Lex(); // Eat the '('.
116     return ParseParenExpr(Res);
117   case asmtok::Minus:
118     Lexer.Lex(); // Eat the operator.
119     if (ParsePrimaryExpr(Res))
120       return true;
121     Res = new AsmUnaryExpr(AsmUnaryExpr::Minus, Res);
122     return false;
123   case asmtok::Plus:
124     Lexer.Lex(); // Eat the operator.
125     if (ParsePrimaryExpr(Res))
126       return true;
127     Res = new AsmUnaryExpr(AsmUnaryExpr::Plus, Res);
128     return false;
129   case asmtok::Tilde:
130     Lexer.Lex(); // Eat the operator.
131     if (ParsePrimaryExpr(Res))
132       return true;
133     Res = new AsmUnaryExpr(AsmUnaryExpr::Not, Res);
134     return false;
135   }
136 }
137
138 /// ParseExpression - Parse an expression and return it.
139 /// 
140 ///  expr ::= expr +,- expr          -> lowest.
141 ///  expr ::= expr |,^,&,! expr      -> middle.
142 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
143 ///  expr ::= primaryexpr
144 ///
145 bool AsmParser::ParseExpression(AsmExpr *&Res) {
146   Res = 0;
147   return ParsePrimaryExpr(Res) ||
148          ParseBinOpRHS(1, Res);
149 }
150
151 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
152   AsmExpr *Expr;
153   
154   SMLoc StartLoc = Lexer.getLoc();
155   if (ParseExpression(Expr))
156     return true;
157
158   if (!Expr->EvaluateAsAbsolute(Ctx, Res))
159     return Error(StartLoc, "expected absolute expression");
160
161   return false;
162 }
163
164 bool AsmParser::ParseRelocatableExpression(MCValue &Res) {
165   AsmExpr *Expr;
166   
167   SMLoc StartLoc = Lexer.getLoc();
168   if (ParseExpression(Expr))
169     return true;
170
171   if (!Expr->EvaluateAsRelocatable(Ctx, Res))
172     return Error(StartLoc, "expected relocatable expression");
173
174   return false;
175 }
176
177 bool AsmParser::ParseParenRelocatableExpression(MCValue &Res) {
178   AsmExpr *Expr;
179   
180   SMLoc StartLoc = Lexer.getLoc();
181   if (ParseParenExpr(Expr))
182     return true;
183
184   if (!Expr->EvaluateAsRelocatable(Ctx, Res))
185     return Error(StartLoc, "expected relocatable expression");
186
187   return false;
188 }
189
190 static unsigned getBinOpPrecedence(asmtok::TokKind K, 
191                                    AsmBinaryExpr::Opcode &Kind) {
192   switch (K) {
193   default: return 0;    // not a binop.
194
195     // Lowest Precedence: &&, ||
196   case asmtok::AmpAmp:
197     Kind = AsmBinaryExpr::LAnd;
198     return 1;
199   case asmtok::PipePipe:
200     Kind = AsmBinaryExpr::LOr;
201     return 1;
202
203     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
204   case asmtok::Plus:
205     Kind = AsmBinaryExpr::Add;
206     return 2;
207   case asmtok::Minus:
208     Kind = AsmBinaryExpr::Sub;
209     return 2;
210   case asmtok::EqualEqual:
211     Kind = AsmBinaryExpr::EQ;
212     return 2;
213   case asmtok::ExclaimEqual:
214   case asmtok::LessGreater:
215     Kind = AsmBinaryExpr::NE;
216     return 2;
217   case asmtok::Less:
218     Kind = AsmBinaryExpr::LT;
219     return 2;
220   case asmtok::LessEqual:
221     Kind = AsmBinaryExpr::LTE;
222     return 2;
223   case asmtok::Greater:
224     Kind = AsmBinaryExpr::GT;
225     return 2;
226   case asmtok::GreaterEqual:
227     Kind = AsmBinaryExpr::GTE;
228     return 2;
229
230     // Intermediate Precedence: |, &, ^
231     //
232     // FIXME: gas seems to support '!' as an infix operator?
233   case asmtok::Pipe:
234     Kind = AsmBinaryExpr::Or;
235     return 3;
236   case asmtok::Caret:
237     Kind = AsmBinaryExpr::Xor;
238     return 3;
239   case asmtok::Amp:
240     Kind = AsmBinaryExpr::And;
241     return 3;
242
243     // Highest Precedence: *, /, %, <<, >>
244   case asmtok::Star:
245     Kind = AsmBinaryExpr::Mul;
246     return 4;
247   case asmtok::Slash:
248     Kind = AsmBinaryExpr::Div;
249     return 4;
250   case asmtok::Percent:
251     Kind = AsmBinaryExpr::Mod;
252     return 4;
253   case asmtok::LessLess:
254     Kind = AsmBinaryExpr::Shl;
255     return 4;
256   case asmtok::GreaterGreater:
257     Kind = AsmBinaryExpr::Shr;
258     return 4;
259   }
260 }
261
262
263 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
264 /// Res contains the LHS of the expression on input.
265 bool AsmParser::ParseBinOpRHS(unsigned Precedence, AsmExpr *&Res) {
266   while (1) {
267     AsmBinaryExpr::Opcode Kind = AsmBinaryExpr::Add;
268     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
269     
270     // If the next token is lower precedence than we are allowed to eat, return
271     // successfully with what we ate already.
272     if (TokPrec < Precedence)
273       return false;
274     
275     Lexer.Lex();
276     
277     // Eat the next primary expression.
278     AsmExpr *RHS;
279     if (ParsePrimaryExpr(RHS)) return true;
280     
281     // If BinOp binds less tightly with RHS than the operator after RHS, let
282     // the pending operator take RHS as its LHS.
283     AsmBinaryExpr::Opcode Dummy;
284     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
285     if (TokPrec < NextTokPrec) {
286       if (ParseBinOpRHS(Precedence+1, RHS)) return true;
287     }
288
289     // Merge LHS and RHS according to operator.
290     Res = new AsmBinaryExpr(Kind, Res, RHS);
291   }
292 }
293
294   
295   
296   
297 /// ParseStatement:
298 ///   ::= EndOfStatement
299 ///   ::= Label* Directive ...Operands... EndOfStatement
300 ///   ::= Label* Identifier OperandList* EndOfStatement
301 bool AsmParser::ParseStatement() {
302   switch (Lexer.getKind()) {
303   default:
304     return TokError("unexpected token at start of statement");
305   case asmtok::EndOfStatement:
306     Lexer.Lex();
307     return false;
308   case asmtok::Identifier:
309     break;
310   // TODO: Recurse on local labels etc.
311   }
312   
313   // If we have an identifier, handle it as the key symbol.
314   SMLoc IDLoc = Lexer.getLoc();
315   const char *IDVal = Lexer.getCurStrVal();
316   
317   // Consume the identifier, see what is after it.
318   switch (Lexer.Lex()) {
319   case asmtok::Colon: {
320     // identifier ':'   -> Label.
321     Lexer.Lex();
322
323     // Diagnose attempt to use a variable as a label.
324     //
325     // FIXME: Diagnostics. Note the location of the definition as a label.
326     // FIXME: This doesn't diagnose assignment to a symbol which has been
327     // implicitly marked as external.
328     MCSymbol *Sym = Ctx.GetOrCreateSymbol(IDVal);
329     if (Sym->getSection())
330       return Error(IDLoc, "invalid symbol redefinition");
331     if (Ctx.GetSymbolValue(Sym))
332       return Error(IDLoc, "symbol already used as assembler variable");
333     
334     // Since we saw a label, create a symbol and emit it.
335     // FIXME: If the label starts with L it is an assembler temporary label.
336     // Why does the client of this api need to know this?
337     Out.EmitLabel(Sym);
338    
339     return ParseStatement();
340   }
341
342   case asmtok::Equal:
343     // identifier '=' ... -> assignment statement
344     Lexer.Lex();
345
346     return ParseAssignment(IDVal, false);
347
348   default: // Normal instruction or directive.
349     break;
350   }
351   
352   // Otherwise, we have a normal instruction or directive.  
353   if (IDVal[0] == '.') {
354     // FIXME: This should be driven based on a hash lookup and callback.
355     if (!strcmp(IDVal, ".section"))
356       return ParseDirectiveDarwinSection();
357     if (!strcmp(IDVal, ".text"))
358       // FIXME: This changes behavior based on the -static flag to the
359       // assembler.
360       return ParseDirectiveSectionSwitch("__TEXT,__text",
361                                          "regular,pure_instructions");
362     if (!strcmp(IDVal, ".const"))
363       return ParseDirectiveSectionSwitch("__TEXT,__const");
364     if (!strcmp(IDVal, ".static_const"))
365       return ParseDirectiveSectionSwitch("__TEXT,__static_const");
366     if (!strcmp(IDVal, ".cstring"))
367       return ParseDirectiveSectionSwitch("__TEXT,__cstring", 
368                                          "cstring_literals");
369     if (!strcmp(IDVal, ".literal4"))
370       return ParseDirectiveSectionSwitch("__TEXT,__literal4", "4byte_literals");
371     if (!strcmp(IDVal, ".literal8"))
372       return ParseDirectiveSectionSwitch("__TEXT,__literal8", "8byte_literals");
373     if (!strcmp(IDVal, ".literal16"))
374       return ParseDirectiveSectionSwitch("__TEXT,__literal16",
375                                          "16byte_literals");
376     if (!strcmp(IDVal, ".constructor"))
377       return ParseDirectiveSectionSwitch("__TEXT,__constructor");
378     if (!strcmp(IDVal, ".destructor"))
379       return ParseDirectiveSectionSwitch("__TEXT,__destructor");
380     if (!strcmp(IDVal, ".fvmlib_init0"))
381       return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init0");
382     if (!strcmp(IDVal, ".fvmlib_init1"))
383       return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init1");
384     if (!strcmp(IDVal, ".symbol_stub")) // FIXME: Different on PPC.
385       return ParseDirectiveSectionSwitch("__IMPORT,__jump_table,symbol_stubs",
386                                     "self_modifying_code+pure_instructions,5");
387     // FIXME: .picsymbol_stub on PPC.
388     if (!strcmp(IDVal, ".data"))
389       return ParseDirectiveSectionSwitch("__DATA,__data");
390     if (!strcmp(IDVal, ".static_data"))
391       return ParseDirectiveSectionSwitch("__DATA,__static_data");
392     if (!strcmp(IDVal, ".non_lazy_symbol_pointer"))
393       return ParseDirectiveSectionSwitch("__DATA,__nl_symbol_pointer",
394                                          "non_lazy_symbol_pointers");
395     if (!strcmp(IDVal, ".lazy_symbol_pointer"))
396       return ParseDirectiveSectionSwitch("__DATA,__la_symbol_pointer",
397                                          "lazy_symbol_pointers");
398     if (!strcmp(IDVal, ".dyld"))
399       return ParseDirectiveSectionSwitch("__DATA,__dyld");
400     if (!strcmp(IDVal, ".mod_init_func"))
401       return ParseDirectiveSectionSwitch("__DATA,__mod_init_func",
402                                          "mod_init_funcs");
403     if (!strcmp(IDVal, ".mod_term_func"))
404       return ParseDirectiveSectionSwitch("__DATA,__mod_term_func",
405                                          "mod_term_funcs");
406     if (!strcmp(IDVal, ".const_data"))
407       return ParseDirectiveSectionSwitch("__DATA,__const", "regular");
408     
409     
410     // FIXME: Verify attributes on sections.
411     if (!strcmp(IDVal, ".objc_class"))
412       return ParseDirectiveSectionSwitch("__OBJC,__class");
413     if (!strcmp(IDVal, ".objc_meta_class"))
414       return ParseDirectiveSectionSwitch("__OBJC,__meta_class");
415     if (!strcmp(IDVal, ".objc_cat_cls_meth"))
416       return ParseDirectiveSectionSwitch("__OBJC,__cat_cls_meth");
417     if (!strcmp(IDVal, ".objc_cat_inst_meth"))
418       return ParseDirectiveSectionSwitch("__OBJC,__cat_inst_meth");
419     if (!strcmp(IDVal, ".objc_protocol"))
420       return ParseDirectiveSectionSwitch("__OBJC,__protocol");
421     if (!strcmp(IDVal, ".objc_string_object"))
422       return ParseDirectiveSectionSwitch("__OBJC,__string_object");
423     if (!strcmp(IDVal, ".objc_cls_meth"))
424       return ParseDirectiveSectionSwitch("__OBJC,__cls_meth");
425     if (!strcmp(IDVal, ".objc_inst_meth"))
426       return ParseDirectiveSectionSwitch("__OBJC,__inst_meth");
427     if (!strcmp(IDVal, ".objc_cls_refs"))
428       return ParseDirectiveSectionSwitch("__OBJC,__cls_refs");
429     if (!strcmp(IDVal, ".objc_message_refs"))
430       return ParseDirectiveSectionSwitch("__OBJC,__message_refs");
431     if (!strcmp(IDVal, ".objc_symbols"))
432       return ParseDirectiveSectionSwitch("__OBJC,__symbols");
433     if (!strcmp(IDVal, ".objc_category"))
434       return ParseDirectiveSectionSwitch("__OBJC,__category");
435     if (!strcmp(IDVal, ".objc_class_vars"))
436       return ParseDirectiveSectionSwitch("__OBJC,__class_vars");
437     if (!strcmp(IDVal, ".objc_instance_vars"))
438       return ParseDirectiveSectionSwitch("__OBJC,__instance_vars");
439     if (!strcmp(IDVal, ".objc_module_info"))
440       return ParseDirectiveSectionSwitch("__OBJC,__module_info");
441     if (!strcmp(IDVal, ".objc_class_names"))
442       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
443     if (!strcmp(IDVal, ".objc_meth_var_types"))
444       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
445     if (!strcmp(IDVal, ".objc_meth_var_names"))
446       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
447     if (!strcmp(IDVal, ".objc_selector_strs"))
448       return ParseDirectiveSectionSwitch("__OBJC,__selector_strs");
449     
450     // Assembler features
451     if (!strcmp(IDVal, ".set"))
452       return ParseDirectiveSet();
453
454     // Data directives
455
456     if (!strcmp(IDVal, ".ascii"))
457       return ParseDirectiveAscii(false);
458     if (!strcmp(IDVal, ".asciz"))
459       return ParseDirectiveAscii(true);
460
461     // FIXME: Target hooks for size? Also for "word", "hword".
462     if (!strcmp(IDVal, ".byte"))
463       return ParseDirectiveValue(1);
464     if (!strcmp(IDVal, ".short"))
465       return ParseDirectiveValue(2);
466     if (!strcmp(IDVal, ".long"))
467       return ParseDirectiveValue(4);
468     if (!strcmp(IDVal, ".quad"))
469       return ParseDirectiveValue(8);
470
471     // FIXME: Target hooks for IsPow2.
472     if (!strcmp(IDVal, ".align"))
473       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
474     if (!strcmp(IDVal, ".align32"))
475       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
476     if (!strcmp(IDVal, ".balign"))
477       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
478     if (!strcmp(IDVal, ".balignw"))
479       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
480     if (!strcmp(IDVal, ".balignl"))
481       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
482     if (!strcmp(IDVal, ".p2align"))
483       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
484     if (!strcmp(IDVal, ".p2alignw"))
485       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
486     if (!strcmp(IDVal, ".p2alignl"))
487       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
488
489     if (!strcmp(IDVal, ".org"))
490       return ParseDirectiveOrg();
491
492     if (!strcmp(IDVal, ".fill"))
493       return ParseDirectiveFill();
494     if (!strcmp(IDVal, ".space"))
495       return ParseDirectiveSpace();
496
497     // Symbol attribute directives
498     if (!strcmp(IDVal, ".globl") || !strcmp(IDVal, ".global"))
499       return ParseDirectiveSymbolAttribute(MCStreamer::Global);
500     if (!strcmp(IDVal, ".hidden"))
501       return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
502     if (!strcmp(IDVal, ".indirect_symbol"))
503       return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
504     if (!strcmp(IDVal, ".internal"))
505       return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
506     if (!strcmp(IDVal, ".lazy_reference"))
507       return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
508     if (!strcmp(IDVal, ".no_dead_strip"))
509       return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
510     if (!strcmp(IDVal, ".private_extern"))
511       return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
512     if (!strcmp(IDVal, ".protected"))
513       return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
514     if (!strcmp(IDVal, ".reference"))
515       return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
516     if (!strcmp(IDVal, ".weak"))
517       return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
518     if (!strcmp(IDVal, ".weak_definition"))
519       return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
520     if (!strcmp(IDVal, ".weak_reference"))
521       return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
522
523     if (!strcmp(IDVal, ".comm"))
524       return ParseDirectiveComm(/*IsLocal=*/false);
525     if (!strcmp(IDVal, ".lcomm"))
526       return ParseDirectiveComm(/*IsLocal=*/true);
527     if (!strcmp(IDVal, ".zerofill"))
528       return ParseDirectiveDarwinZerofill();
529     if (!strcmp(IDVal, ".desc"))
530       return ParseDirectiveDarwinSymbolDesc();
531     if (!strcmp(IDVal, ".lsym"))
532       return ParseDirectiveDarwinLsym();
533
534     if (!strcmp(IDVal, ".subsections_via_symbols"))
535       return ParseDirectiveDarwinSubsectionsViaSymbols();
536     if (!strcmp(IDVal, ".abort"))
537       return ParseDirectiveAbort();
538     if (!strcmp(IDVal, ".include"))
539       return ParseDirectiveInclude();
540
541     Warning(IDLoc, "ignoring directive for now");
542     EatToEndOfStatement();
543     return false;
544   }
545
546   MCInst Inst;
547   if (ParseX86InstOperands(IDVal, Inst))
548     return true;
549   
550   if (Lexer.isNot(asmtok::EndOfStatement))
551     return TokError("unexpected token in argument list");
552
553   // Eat the end of statement marker.
554   Lexer.Lex();
555   
556   // Instruction is good, process it.
557   Out.EmitInstruction(Inst);
558   
559   // Skip to end of line for now.
560   return false;
561 }
562
563 bool AsmParser::ParseAssignment(const char *Name, bool IsDotSet) {
564   // FIXME: Use better location, we should use proper tokens.
565   SMLoc EqualLoc = Lexer.getLoc();
566
567   MCValue Value;
568   if (ParseRelocatableExpression(Value))
569     return true;
570   
571   if (Lexer.isNot(asmtok::EndOfStatement))
572     return TokError("unexpected token in assignment");
573
574   // Eat the end of statement marker.
575   Lexer.Lex();
576
577   // Diagnose assignment to a label.
578   //
579   // FIXME: Diagnostics. Note the location of the definition as a label.
580   // FIXME: This doesn't diagnose assignment to a symbol which has been
581   // implicitly marked as external.
582   // FIXME: Handle '.'.
583   // FIXME: Diagnose assignment to protected identifier (e.g., register name).
584   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
585   if (Sym->getSection())
586     return Error(EqualLoc, "invalid assignment to symbol emitted as a label");
587   if (Sym->isExternal())
588     return Error(EqualLoc, "invalid assignment to external symbol");
589
590   // Do the assignment.
591   Out.EmitAssignment(Sym, Value, IsDotSet);
592
593   return false;
594 }
595
596 /// ParseDirectiveSet:
597 ///   ::= .set identifier ',' expression
598 bool AsmParser::ParseDirectiveSet() {
599   if (Lexer.isNot(asmtok::Identifier))
600     return TokError("expected identifier after '.set' directive");
601
602   const char *Name = Lexer.getCurStrVal();
603   
604   if (Lexer.Lex() != asmtok::Comma)
605     return TokError("unexpected token in '.set'");
606   Lexer.Lex();
607
608   return ParseAssignment(Name, true);
609 }
610
611 /// ParseDirectiveSection:
612 ///   ::= .section identifier (',' identifier)*
613 /// FIXME: This should actually parse out the segment, section, attributes and
614 /// sizeof_stub fields.
615 bool AsmParser::ParseDirectiveDarwinSection() {
616   if (Lexer.isNot(asmtok::Identifier))
617     return TokError("expected identifier after '.section' directive");
618   
619   std::string Section = Lexer.getCurStrVal();
620   Lexer.Lex();
621   
622   // Accept a comma separated list of modifiers.
623   while (Lexer.is(asmtok::Comma)) {
624     Lexer.Lex();
625     
626     if (Lexer.isNot(asmtok::Identifier))
627       return TokError("expected identifier in '.section' directive");
628     Section += ',';
629     Section += Lexer.getCurStrVal();
630     Lexer.Lex();
631   }
632   
633   if (Lexer.isNot(asmtok::EndOfStatement))
634     return TokError("unexpected token in '.section' directive");
635   Lexer.Lex();
636
637   Out.SwitchSection(Ctx.GetSection(Section.c_str()));
638   return false;
639 }
640
641 bool AsmParser::ParseDirectiveSectionSwitch(const char *Section,
642                                             const char *Directives) {
643   if (Lexer.isNot(asmtok::EndOfStatement))
644     return TokError("unexpected token in section switching directive");
645   Lexer.Lex();
646   
647   std::string SectionStr = Section;
648   if (Directives && Directives[0]) {
649     SectionStr += ","; 
650     SectionStr += Directives;
651   }
652   
653   Out.SwitchSection(Ctx.GetSection(Section));
654   return false;
655 }
656
657 /// ParseDirectiveAscii:
658 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
659 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
660   if (Lexer.isNot(asmtok::EndOfStatement)) {
661     for (;;) {
662       if (Lexer.isNot(asmtok::String))
663         return TokError("expected string in '.ascii' or '.asciz' directive");
664       
665       // FIXME: This shouldn't use a const char* + strlen, the string could have
666       // embedded nulls.
667       // FIXME: Should have accessor for getting string contents.
668       const char *Str = Lexer.getCurStrVal();
669       Out.EmitBytes(Str + 1, strlen(Str) - 2);
670       if (ZeroTerminated)
671         Out.EmitBytes("\0", 1);
672       
673       Lexer.Lex();
674       
675       if (Lexer.is(asmtok::EndOfStatement))
676         break;
677
678       if (Lexer.isNot(asmtok::Comma))
679         return TokError("unexpected token in '.ascii' or '.asciz' directive");
680       Lexer.Lex();
681     }
682   }
683
684   Lexer.Lex();
685   return false;
686 }
687
688 /// ParseDirectiveValue
689 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
690 bool AsmParser::ParseDirectiveValue(unsigned Size) {
691   if (Lexer.isNot(asmtok::EndOfStatement)) {
692     for (;;) {
693       MCValue Expr;
694       if (ParseRelocatableExpression(Expr))
695         return true;
696
697       Out.EmitValue(Expr, Size);
698
699       if (Lexer.is(asmtok::EndOfStatement))
700         break;
701       
702       // FIXME: Improve diagnostic.
703       if (Lexer.isNot(asmtok::Comma))
704         return TokError("unexpected token in directive");
705       Lexer.Lex();
706     }
707   }
708
709   Lexer.Lex();
710   return false;
711 }
712
713 /// ParseDirectiveSpace
714 ///  ::= .space expression [ , expression ]
715 bool AsmParser::ParseDirectiveSpace() {
716   int64_t NumBytes;
717   if (ParseAbsoluteExpression(NumBytes))
718     return true;
719
720   int64_t FillExpr = 0;
721   bool HasFillExpr = false;
722   if (Lexer.isNot(asmtok::EndOfStatement)) {
723     if (Lexer.isNot(asmtok::Comma))
724       return TokError("unexpected token in '.space' directive");
725     Lexer.Lex();
726     
727     if (ParseAbsoluteExpression(FillExpr))
728       return true;
729
730     HasFillExpr = true;
731
732     if (Lexer.isNot(asmtok::EndOfStatement))
733       return TokError("unexpected token in '.space' directive");
734   }
735
736   Lexer.Lex();
737
738   if (NumBytes <= 0)
739     return TokError("invalid number of bytes in '.space' directive");
740
741   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
742   for (uint64_t i = 0, e = NumBytes; i != e; ++i)
743     Out.EmitValue(MCValue::get(FillExpr), 1);
744
745   return false;
746 }
747
748 /// ParseDirectiveFill
749 ///  ::= .fill expression , expression , expression
750 bool AsmParser::ParseDirectiveFill() {
751   int64_t NumValues;
752   if (ParseAbsoluteExpression(NumValues))
753     return true;
754
755   if (Lexer.isNot(asmtok::Comma))
756     return TokError("unexpected token in '.fill' directive");
757   Lexer.Lex();
758   
759   int64_t FillSize;
760   if (ParseAbsoluteExpression(FillSize))
761     return true;
762
763   if (Lexer.isNot(asmtok::Comma))
764     return TokError("unexpected token in '.fill' directive");
765   Lexer.Lex();
766   
767   int64_t FillExpr;
768   if (ParseAbsoluteExpression(FillExpr))
769     return true;
770
771   if (Lexer.isNot(asmtok::EndOfStatement))
772     return TokError("unexpected token in '.fill' directive");
773   
774   Lexer.Lex();
775
776   if (FillSize != 1 && FillSize != 2 && FillSize != 4)
777     return TokError("invalid '.fill' size, expected 1, 2, or 4");
778
779   for (uint64_t i = 0, e = NumValues; i != e; ++i)
780     Out.EmitValue(MCValue::get(FillExpr), FillSize);
781
782   return false;
783 }
784
785 /// ParseDirectiveOrg
786 ///  ::= .org expression [ , expression ]
787 bool AsmParser::ParseDirectiveOrg() {
788   MCValue Offset;
789   if (ParseRelocatableExpression(Offset))
790     return true;
791
792   // Parse optional fill expression.
793   int64_t FillExpr = 0;
794   if (Lexer.isNot(asmtok::EndOfStatement)) {
795     if (Lexer.isNot(asmtok::Comma))
796       return TokError("unexpected token in '.org' directive");
797     Lexer.Lex();
798     
799     if (ParseAbsoluteExpression(FillExpr))
800       return true;
801
802     if (Lexer.isNot(asmtok::EndOfStatement))
803       return TokError("unexpected token in '.org' directive");
804   }
805
806   Lexer.Lex();
807
808   // FIXME: Only limited forms of relocatable expressions are accepted here, it
809   // has to be relative to the current section.
810   Out.EmitValueToOffset(Offset, FillExpr);
811
812   return false;
813 }
814
815 /// ParseDirectiveAlign
816 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
817 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
818   int64_t Alignment;
819   if (ParseAbsoluteExpression(Alignment))
820     return true;
821
822   SMLoc MaxBytesLoc;
823   bool HasFillExpr = false;
824   int64_t FillExpr = 0;
825   int64_t MaxBytesToFill = 0;
826   if (Lexer.isNot(asmtok::EndOfStatement)) {
827     if (Lexer.isNot(asmtok::Comma))
828       return TokError("unexpected token in directive");
829     Lexer.Lex();
830
831     // The fill expression can be omitted while specifying a maximum number of
832     // alignment bytes, e.g:
833     //  .align 3,,4
834     if (Lexer.isNot(asmtok::Comma)) {
835       HasFillExpr = true;
836       if (ParseAbsoluteExpression(FillExpr))
837         return true;
838     }
839
840     if (Lexer.isNot(asmtok::EndOfStatement)) {
841       if (Lexer.isNot(asmtok::Comma))
842         return TokError("unexpected token in directive");
843       Lexer.Lex();
844
845       MaxBytesLoc = Lexer.getLoc();
846       if (ParseAbsoluteExpression(MaxBytesToFill))
847         return true;
848       
849       if (Lexer.isNot(asmtok::EndOfStatement))
850         return TokError("unexpected token in directive");
851     }
852   }
853
854   Lexer.Lex();
855
856   if (!HasFillExpr) {
857     // FIXME: Sometimes fill with nop.
858     FillExpr = 0;
859   }
860
861   // Compute alignment in bytes.
862   if (IsPow2) {
863     // FIXME: Diagnose overflow.
864     Alignment = 1LL << Alignment;
865   }
866
867   // Diagnose non-sensical max bytes to fill.
868   if (MaxBytesLoc.isValid()) {
869     if (MaxBytesToFill < 1) {
870       Warning(MaxBytesLoc, "alignment directive can never be satisfied in this "
871               "many bytes, ignoring");
872       return false;
873     }
874
875     if (MaxBytesToFill >= Alignment) {
876       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
877               "has no effect");
878       MaxBytesToFill = 0;
879     }
880   }
881
882   // FIXME: Target specific behavior about how the "extra" bytes are filled.
883   Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
884
885   return false;
886 }
887
888 /// ParseDirectiveSymbolAttribute
889 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
890 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
891   if (Lexer.isNot(asmtok::EndOfStatement)) {
892     for (;;) {
893       if (Lexer.isNot(asmtok::Identifier))
894         return TokError("expected identifier in directive");
895       
896       MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
897       Lexer.Lex();
898
899       // If this is use of an undefined symbol then mark it external.
900       if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
901         Sym->setExternal(true);
902
903       Out.EmitSymbolAttribute(Sym, Attr);
904
905       if (Lexer.is(asmtok::EndOfStatement))
906         break;
907
908       if (Lexer.isNot(asmtok::Comma))
909         return TokError("unexpected token in directive");
910       Lexer.Lex();
911     }
912   }
913
914   Lexer.Lex();
915   return false;  
916 }
917
918 /// ParseDirectiveDarwinSymbolDesc
919 ///  ::= .desc identifier , expression
920 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
921   if (Lexer.isNot(asmtok::Identifier))
922     return TokError("expected identifier in directive");
923   
924   // handle the identifier as the key symbol.
925   SMLoc IDLoc = Lexer.getLoc();
926   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
927   Lexer.Lex();
928
929   if (Lexer.isNot(asmtok::Comma))
930     return TokError("unexpected token in '.desc' directive");
931   Lexer.Lex();
932
933   SMLoc DescLoc = Lexer.getLoc();
934   int64_t DescValue;
935   if (ParseAbsoluteExpression(DescValue))
936     return true;
937
938   if (Lexer.isNot(asmtok::EndOfStatement))
939     return TokError("unexpected token in '.desc' directive");
940   
941   Lexer.Lex();
942
943   // Set the n_desc field of this Symbol to this DescValue
944   Out.EmitSymbolDesc(Sym, DescValue);
945
946   return false;
947 }
948
949 /// ParseDirectiveComm
950 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
951 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
952   if (Lexer.isNot(asmtok::Identifier))
953     return TokError("expected identifier in directive");
954   
955   // handle the identifier as the key symbol.
956   SMLoc IDLoc = Lexer.getLoc();
957   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
958   Lexer.Lex();
959
960   if (Lexer.isNot(asmtok::Comma))
961     return TokError("unexpected token in directive");
962   Lexer.Lex();
963
964   int64_t Size;
965   SMLoc SizeLoc = Lexer.getLoc();
966   if (ParseAbsoluteExpression(Size))
967     return true;
968
969   int64_t Pow2Alignment = 0;
970   SMLoc Pow2AlignmentLoc;
971   if (Lexer.is(asmtok::Comma)) {
972     Lexer.Lex();
973     Pow2AlignmentLoc = Lexer.getLoc();
974     if (ParseAbsoluteExpression(Pow2Alignment))
975       return true;
976   }
977   
978   if (Lexer.isNot(asmtok::EndOfStatement))
979     return TokError("unexpected token in '.comm' or '.lcomm' directive");
980   
981   Lexer.Lex();
982
983   // NOTE: a size of zero for a .comm should create a undefined symbol
984   // but a size of .lcomm creates a bss symbol of size zero.
985   if (Size < 0)
986     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
987                  "be less than zero");
988
989   // NOTE: The alignment in the directive is a power of 2 value, the assember
990   // may internally end up wanting an alignment in bytes.
991   // FIXME: Diagnose overflow.
992   if (Pow2Alignment < 0)
993     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
994                  "alignment, can't be less than zero");
995
996   // TODO: Symbol must be undefined or it is a error to re-defined the symbol
997   if (Sym->getSection() || Ctx.GetSymbolValue(Sym))
998     return Error(IDLoc, "invalid symbol redefinition");
999
1000   // Create the Symbol as a common or local common with Size and Pow2Alignment
1001   Out.EmitCommonSymbol(Sym, Size, Pow2Alignment, IsLocal);
1002
1003   return false;
1004 }
1005
1006 /// ParseDirectiveDarwinZerofill
1007 ///  ::= .zerofill segname , sectname [, identifier , size_expression [
1008 ///      , align_expression ]]
1009 bool AsmParser::ParseDirectiveDarwinZerofill() {
1010   if (Lexer.isNot(asmtok::Identifier))
1011     return TokError("expected segment name after '.zerofill' directive");
1012   std::string Section = Lexer.getCurStrVal();
1013   Lexer.Lex();
1014
1015   if (Lexer.isNot(asmtok::Comma))
1016     return TokError("unexpected token in directive");
1017   Section += ',';
1018   Lexer.Lex();
1019  
1020   if (Lexer.isNot(asmtok::Identifier))
1021     return TokError("expected section name after comma in '.zerofill' "
1022                     "directive");
1023   Section += Lexer.getCurStrVal();
1024   Lexer.Lex();
1025
1026   // FIXME: we will need to tell GetSection() that this is to be created with or
1027   // must have the Mach-O section type of S_ZEROFILL.  Something like the code
1028   // below could be done but for now it is not as EmitZerofill() does not know
1029   // how to deal with a section type in the section name like
1030   // ParseDirectiveDarwinSection() allows.
1031   // Section += ',';
1032   // Section += "zerofill";
1033
1034   // If this is the end of the line all that was wanted was to create the
1035   // the section but with no symbol.
1036   if (Lexer.is(asmtok::EndOfStatement)) {
1037     // Create the zerofill section but no symbol
1038     Out.EmitZerofill(Ctx.GetSection(Section.c_str()));
1039     return false;
1040   }
1041
1042   if (Lexer.isNot(asmtok::Comma))
1043     return TokError("unexpected token in directive");
1044   Lexer.Lex();
1045
1046   if (Lexer.isNot(asmtok::Identifier))
1047     return TokError("expected identifier in directive");
1048   
1049   // handle the identifier as the key symbol.
1050   SMLoc IDLoc = Lexer.getLoc();
1051   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
1052   Lexer.Lex();
1053
1054   if (Lexer.isNot(asmtok::Comma))
1055     return TokError("unexpected token in directive");
1056   Lexer.Lex();
1057
1058   int64_t Size;
1059   SMLoc SizeLoc = Lexer.getLoc();
1060   if (ParseAbsoluteExpression(Size))
1061     return true;
1062
1063   int64_t Pow2Alignment = 0;
1064   SMLoc Pow2AlignmentLoc;
1065   if (Lexer.is(asmtok::Comma)) {
1066     Lexer.Lex();
1067     Pow2AlignmentLoc = Lexer.getLoc();
1068     if (ParseAbsoluteExpression(Pow2Alignment))
1069       return true;
1070   }
1071   
1072   if (Lexer.isNot(asmtok::EndOfStatement))
1073     return TokError("unexpected token in '.zerofill' directive");
1074   
1075   Lexer.Lex();
1076
1077   if (Size < 0)
1078     return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1079                  "than zero");
1080
1081   // NOTE: The alignment in the directive is a power of 2 value, the assember
1082   // may internally end up wanting an alignment in bytes.
1083   // FIXME: Diagnose overflow.
1084   if (Pow2Alignment < 0)
1085     return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1086                  "can't be less than zero");
1087
1088   // TODO: Symbol must be undefined or it is a error to re-defined the symbol
1089   if (Sym->getSection() || Ctx.GetSymbolValue(Sym))
1090     return Error(IDLoc, "invalid symbol redefinition");
1091
1092   // Create the zerofill Symbol with Size and Pow2Alignment
1093   Out.EmitZerofill(Ctx.GetSection(Section.c_str()), Sym, Size, Pow2Alignment);
1094
1095   return false;
1096 }
1097
1098 /// ParseDirectiveDarwinSubsectionsViaSymbols
1099 ///  ::= .subsections_via_symbols
1100 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1101   if (Lexer.isNot(asmtok::EndOfStatement))
1102     return TokError("unexpected token in '.subsections_via_symbols' directive");
1103   
1104   Lexer.Lex();
1105
1106   Out.SubsectionsViaSymbols();
1107
1108   return false;
1109 }
1110
1111 /// ParseDirectiveAbort
1112 ///  ::= .abort [ "abort_string" ]
1113 bool AsmParser::ParseDirectiveAbort() {
1114   const char *Str = NULL;
1115   if (Lexer.isNot(asmtok::EndOfStatement)) {
1116     if (Lexer.isNot(asmtok::String))
1117       return TokError("expected string in '.abort' directive");
1118     
1119     Str = Lexer.getCurStrVal();
1120
1121     Lexer.Lex();
1122   }
1123
1124   if (Lexer.isNot(asmtok::EndOfStatement))
1125     return TokError("unexpected token in '.abort' directive");
1126   
1127   Lexer.Lex();
1128
1129   Out.AbortAssembly(Str);
1130
1131   return false;
1132 }
1133
1134 /// ParseDirectiveLsym
1135 ///  ::= .lsym identifier , expression
1136 bool AsmParser::ParseDirectiveDarwinLsym() {
1137   if (Lexer.isNot(asmtok::Identifier))
1138     return TokError("expected identifier in directive");
1139   
1140   // handle the identifier as the key symbol.
1141   SMLoc IDLoc = Lexer.getLoc();
1142   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
1143   Lexer.Lex();
1144
1145   if (Lexer.isNot(asmtok::Comma))
1146     return TokError("unexpected token in '.lsym' directive");
1147   Lexer.Lex();
1148
1149   MCValue Expr;
1150   if (ParseRelocatableExpression(Expr))
1151     return true;
1152
1153   if (Lexer.isNot(asmtok::EndOfStatement))
1154     return TokError("unexpected token in '.lsym' directive");
1155   
1156   Lexer.Lex();
1157
1158   // Create the Sym with the value of the Expr
1159   Out.EmitLocalSymbol(Sym, Expr);
1160
1161   return false;
1162 }
1163
1164 /// ParseDirectiveInclude
1165 ///  ::= .include "filename"
1166 bool AsmParser::ParseDirectiveInclude() {
1167   const char *Str;
1168
1169   if (Lexer.isNot(asmtok::String))
1170     return TokError("expected string in '.include' directive");
1171   
1172   Str = Lexer.getCurStrVal();
1173
1174   Lexer.Lex();
1175
1176   if (Lexer.isNot(asmtok::EndOfStatement))
1177     return TokError("unexpected token in '.include' directive");
1178   
1179   Lexer.Lex();
1180
1181   Out.SwitchInputAssemblyFile(Str);
1182
1183   return false;
1184 }