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