Switch AsmLexer::Lex to returning a reference to the current token.
[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.getTok().getString());
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.getTok().getIntVal());
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   AsmToken ID = Lexer.getTok();
317   SMLoc IDLoc = ID.getLoc();
318   StringRef IDVal = ID.getString();
319   
320   // Consume the identifier, see what is after it.
321   switch (Lexer.Lex().getKind()) {
322   case AsmToken::Colon: {
323     // identifier ':'   -> Label.
324     Lexer.Lex();
325
326     // Diagnose attempt to use a variable as a label.
327     //
328     // FIXME: Diagnostics. Note the location of the definition as a label.
329     // FIXME: This doesn't diagnose assignment to a symbol which has been
330     // implicitly marked as external.
331     MCSymbol *Sym = Ctx.GetOrCreateSymbol(IDVal);
332     if (Sym->getSection())
333       return Error(IDLoc, "invalid symbol redefinition");
334     if (Ctx.GetSymbolValue(Sym))
335       return Error(IDLoc, "symbol already used as assembler variable");
336     
337     // Since we saw a label, create a symbol and emit it.
338     // FIXME: If the label starts with L it is an assembler temporary label.
339     // Why does the client of this api need to know this?
340     Out.EmitLabel(Sym);
341    
342     return ParseStatement();
343   }
344
345   case AsmToken::Equal:
346     // identifier '=' ... -> assignment statement
347     Lexer.Lex();
348
349     return ParseAssignment(IDVal, false);
350
351   default: // Normal instruction or directive.
352     break;
353   }
354   
355   // Otherwise, we have a normal instruction or directive.  
356   if (IDVal[0] == '.') {
357     // FIXME: This should be driven based on a hash lookup and callback.
358     if (IDVal == ".section")
359       return ParseDirectiveDarwinSection();
360     if (IDVal == ".text")
361       // FIXME: This changes behavior based on the -static flag to the
362       // assembler.
363       return ParseDirectiveSectionSwitch("__TEXT,__text",
364                                          "regular,pure_instructions");
365     if (IDVal == ".const")
366       return ParseDirectiveSectionSwitch("__TEXT,__const");
367     if (IDVal == ".static_const")
368       return ParseDirectiveSectionSwitch("__TEXT,__static_const");
369     if (IDVal == ".cstring")
370       return ParseDirectiveSectionSwitch("__TEXT,__cstring", 
371                                          "cstring_literals");
372     if (IDVal == ".literal4")
373       return ParseDirectiveSectionSwitch("__TEXT,__literal4", "4byte_literals");
374     if (IDVal == ".literal8")
375       return ParseDirectiveSectionSwitch("__TEXT,__literal8", "8byte_literals");
376     if (IDVal == ".literal16")
377       return ParseDirectiveSectionSwitch("__TEXT,__literal16",
378                                          "16byte_literals");
379     if (IDVal == ".constructor")
380       return ParseDirectiveSectionSwitch("__TEXT,__constructor");
381     if (IDVal == ".destructor")
382       return ParseDirectiveSectionSwitch("__TEXT,__destructor");
383     if (IDVal == ".fvmlib_init0")
384       return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init0");
385     if (IDVal == ".fvmlib_init1")
386       return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init1");
387     if (IDVal == ".symbol_stub") // FIXME: Different on PPC.
388       return ParseDirectiveSectionSwitch("__IMPORT,__jump_table,symbol_stubs",
389                                     "self_modifying_code+pure_instructions,5");
390     // FIXME: .picsymbol_stub on PPC.
391     if (IDVal == ".data")
392       return ParseDirectiveSectionSwitch("__DATA,__data");
393     if (IDVal == ".static_data")
394       return ParseDirectiveSectionSwitch("__DATA,__static_data");
395     if (IDVal == ".non_lazy_symbol_pointer")
396       return ParseDirectiveSectionSwitch("__DATA,__nl_symbol_pointer",
397                                          "non_lazy_symbol_pointers");
398     if (IDVal == ".lazy_symbol_pointer")
399       return ParseDirectiveSectionSwitch("__DATA,__la_symbol_pointer",
400                                          "lazy_symbol_pointers");
401     if (IDVal == ".dyld")
402       return ParseDirectiveSectionSwitch("__DATA,__dyld");
403     if (IDVal == ".mod_init_func")
404       return ParseDirectiveSectionSwitch("__DATA,__mod_init_func",
405                                          "mod_init_funcs");
406     if (IDVal == ".mod_term_func")
407       return ParseDirectiveSectionSwitch("__DATA,__mod_term_func",
408                                          "mod_term_funcs");
409     if (IDVal == ".const_data")
410       return ParseDirectiveSectionSwitch("__DATA,__const", "regular");
411     
412     
413     // FIXME: Verify attributes on sections.
414     if (IDVal == ".objc_class")
415       return ParseDirectiveSectionSwitch("__OBJC,__class");
416     if (IDVal == ".objc_meta_class")
417       return ParseDirectiveSectionSwitch("__OBJC,__meta_class");
418     if (IDVal == ".objc_cat_cls_meth")
419       return ParseDirectiveSectionSwitch("__OBJC,__cat_cls_meth");
420     if (IDVal == ".objc_cat_inst_meth")
421       return ParseDirectiveSectionSwitch("__OBJC,__cat_inst_meth");
422     if (IDVal == ".objc_protocol")
423       return ParseDirectiveSectionSwitch("__OBJC,__protocol");
424     if (IDVal == ".objc_string_object")
425       return ParseDirectiveSectionSwitch("__OBJC,__string_object");
426     if (IDVal == ".objc_cls_meth")
427       return ParseDirectiveSectionSwitch("__OBJC,__cls_meth");
428     if (IDVal == ".objc_inst_meth")
429       return ParseDirectiveSectionSwitch("__OBJC,__inst_meth");
430     if (IDVal == ".objc_cls_refs")
431       return ParseDirectiveSectionSwitch("__OBJC,__cls_refs");
432     if (IDVal == ".objc_message_refs")
433       return ParseDirectiveSectionSwitch("__OBJC,__message_refs");
434     if (IDVal == ".objc_symbols")
435       return ParseDirectiveSectionSwitch("__OBJC,__symbols");
436     if (IDVal == ".objc_category")
437       return ParseDirectiveSectionSwitch("__OBJC,__category");
438     if (IDVal == ".objc_class_vars")
439       return ParseDirectiveSectionSwitch("__OBJC,__class_vars");
440     if (IDVal == ".objc_instance_vars")
441       return ParseDirectiveSectionSwitch("__OBJC,__instance_vars");
442     if (IDVal == ".objc_module_info")
443       return ParseDirectiveSectionSwitch("__OBJC,__module_info");
444     if (IDVal == ".objc_class_names")
445       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
446     if (IDVal == ".objc_meth_var_types")
447       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
448     if (IDVal == ".objc_meth_var_names")
449       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
450     if (IDVal == ".objc_selector_strs")
451       return ParseDirectiveSectionSwitch("__OBJC,__selector_strs");
452     
453     // Assembler features
454     if (IDVal == ".set")
455       return ParseDirectiveSet();
456
457     // Data directives
458
459     if (IDVal == ".ascii")
460       return ParseDirectiveAscii(false);
461     if (IDVal == ".asciz")
462       return ParseDirectiveAscii(true);
463
464     // FIXME: Target hooks for size? Also for "word", "hword".
465     if (IDVal == ".byte")
466       return ParseDirectiveValue(1);
467     if (IDVal == ".short")
468       return ParseDirectiveValue(2);
469     if (IDVal == ".long")
470       return ParseDirectiveValue(4);
471     if (IDVal == ".quad")
472       return ParseDirectiveValue(8);
473
474     // FIXME: Target hooks for IsPow2.
475     if (IDVal == ".align")
476       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
477     if (IDVal == ".align32")
478       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
479     if (IDVal == ".balign")
480       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
481     if (IDVal == ".balignw")
482       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
483     if (IDVal == ".balignl")
484       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
485     if (IDVal == ".p2align")
486       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
487     if (IDVal == ".p2alignw")
488       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
489     if (IDVal == ".p2alignl")
490       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
491
492     if (IDVal == ".org")
493       return ParseDirectiveOrg();
494
495     if (IDVal == ".fill")
496       return ParseDirectiveFill();
497     if (IDVal == ".space")
498       return ParseDirectiveSpace();
499
500     // Symbol attribute directives
501     if (IDVal == ".globl" || IDVal == ".global")
502       return ParseDirectiveSymbolAttribute(MCStreamer::Global);
503     if (IDVal == ".hidden")
504       return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
505     if (IDVal == ".indirect_symbol")
506       return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
507     if (IDVal == ".internal")
508       return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
509     if (IDVal == ".lazy_reference")
510       return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
511     if (IDVal == ".no_dead_strip")
512       return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
513     if (IDVal == ".private_extern")
514       return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
515     if (IDVal == ".protected")
516       return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
517     if (IDVal == ".reference")
518       return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
519     if (IDVal == ".weak")
520       return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
521     if (IDVal == ".weak_definition")
522       return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
523     if (IDVal == ".weak_reference")
524       return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
525
526     if (IDVal == ".comm")
527       return ParseDirectiveComm(/*IsLocal=*/false);
528     if (IDVal == ".lcomm")
529       return ParseDirectiveComm(/*IsLocal=*/true);
530     if (IDVal == ".zerofill")
531       return ParseDirectiveDarwinZerofill();
532     if (IDVal == ".desc")
533       return ParseDirectiveDarwinSymbolDesc();
534     if (IDVal == ".lsym")
535       return ParseDirectiveDarwinLsym();
536
537     if (IDVal == ".subsections_via_symbols")
538       return ParseDirectiveDarwinSubsectionsViaSymbols();
539     if (IDVal == ".abort")
540       return ParseDirectiveAbort();
541     if (IDVal == ".include")
542       return ParseDirectiveInclude();
543     if (IDVal == ".dump")
544       return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
545     if (IDVal == ".load")
546       return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
547
548     Warning(IDLoc, "ignoring directive for now");
549     EatToEndOfStatement();
550     return false;
551   }
552
553   MCInst Inst;
554   if (ParseX86InstOperands(IDVal, Inst) &&
555       getTargetParser().ParseInstruction(*this, IDVal, Inst))
556     return true;
557   
558   if (Lexer.isNot(AsmToken::EndOfStatement))
559     return TokError("unexpected token in argument list");
560
561   // Eat the end of statement marker.
562   Lexer.Lex();
563   
564   // Instruction is good, process it.
565   Out.EmitInstruction(Inst);
566   
567   // Skip to end of line for now.
568   return false;
569 }
570
571 bool AsmParser::ParseAssignment(const StringRef &Name, bool IsDotSet) {
572   // FIXME: Use better location, we should use proper tokens.
573   SMLoc EqualLoc = Lexer.getLoc();
574
575   MCValue Value;
576   if (ParseRelocatableExpression(Value))
577     return true;
578   
579   if (Lexer.isNot(AsmToken::EndOfStatement))
580     return TokError("unexpected token in assignment");
581
582   // Eat the end of statement marker.
583   Lexer.Lex();
584
585   // Diagnose assignment to a label.
586   //
587   // FIXME: Diagnostics. Note the location of the definition as a label.
588   // FIXME: This doesn't diagnose assignment to a symbol which has been
589   // implicitly marked as external.
590   // FIXME: Handle '.'.
591   // FIXME: Diagnose assignment to protected identifier (e.g., register name).
592   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
593   if (Sym->getSection())
594     return Error(EqualLoc, "invalid assignment to symbol emitted as a label");
595   if (Sym->isExternal())
596     return Error(EqualLoc, "invalid assignment to external symbol");
597
598   // Do the assignment.
599   Out.EmitAssignment(Sym, Value, IsDotSet);
600
601   return false;
602 }
603
604 /// ParseDirectiveSet:
605 ///   ::= .set identifier ',' expression
606 bool AsmParser::ParseDirectiveSet() {
607   if (Lexer.isNot(AsmToken::Identifier))
608     return TokError("expected identifier after '.set' directive");
609
610   StringRef Name = Lexer.getTok().getString();
611   
612   if (Lexer.Lex().isNot(AsmToken::Comma))
613     return TokError("unexpected token in '.set'");
614   Lexer.Lex();
615
616   return ParseAssignment(Name, true);
617 }
618
619 /// ParseDirectiveSection:
620 ///   ::= .section identifier (',' identifier)*
621 /// FIXME: This should actually parse out the segment, section, attributes and
622 /// sizeof_stub fields.
623 bool AsmParser::ParseDirectiveDarwinSection() {
624   if (Lexer.isNot(AsmToken::Identifier))
625     return TokError("expected identifier after '.section' directive");
626   
627   std::string Section = Lexer.getTok().getString();
628   Lexer.Lex();
629   
630   // Accept a comma separated list of modifiers.
631   while (Lexer.is(AsmToken::Comma)) {
632     Lexer.Lex();
633     
634     if (Lexer.isNot(AsmToken::Identifier))
635       return TokError("expected identifier in '.section' directive");
636     Section += ',';
637     Section += Lexer.getTok().getString().str();
638     Lexer.Lex();
639   }
640   
641   if (Lexer.isNot(AsmToken::EndOfStatement))
642     return TokError("unexpected token in '.section' directive");
643   Lexer.Lex();
644
645   Out.SwitchSection(Ctx.GetSection(Section.c_str()));
646   return false;
647 }
648
649 bool AsmParser::ParseDirectiveSectionSwitch(const char *Section,
650                                             const char *Directives) {
651   if (Lexer.isNot(AsmToken::EndOfStatement))
652     return TokError("unexpected token in section switching directive");
653   Lexer.Lex();
654   
655   std::string SectionStr = Section;
656   if (Directives && Directives[0]) {
657     SectionStr += ","; 
658     SectionStr += Directives;
659   }
660   
661   Out.SwitchSection(Ctx.GetSection(Section));
662   return false;
663 }
664
665 /// ParseDirectiveAscii:
666 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
667 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
668   if (Lexer.isNot(AsmToken::EndOfStatement)) {
669     for (;;) {
670       if (Lexer.isNot(AsmToken::String))
671         return TokError("expected string in '.ascii' or '.asciz' directive");
672       
673       // FIXME: This shouldn't use a const char* + strlen, the string could have
674       // embedded nulls.
675       // FIXME: Should have accessor for getting string contents.
676       StringRef Str = Lexer.getTok().getString();
677       Out.EmitBytes(Str.substr(1, Str.size() - 2));
678       if (ZeroTerminated)
679         Out.EmitBytes(StringRef("\0", 1));
680       
681       Lexer.Lex();
682       
683       if (Lexer.is(AsmToken::EndOfStatement))
684         break;
685
686       if (Lexer.isNot(AsmToken::Comma))
687         return TokError("unexpected token in '.ascii' or '.asciz' directive");
688       Lexer.Lex();
689     }
690   }
691
692   Lexer.Lex();
693   return false;
694 }
695
696 /// ParseDirectiveValue
697 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
698 bool AsmParser::ParseDirectiveValue(unsigned Size) {
699   if (Lexer.isNot(AsmToken::EndOfStatement)) {
700     for (;;) {
701       MCValue Expr;
702       if (ParseRelocatableExpression(Expr))
703         return true;
704
705       Out.EmitValue(Expr, Size);
706
707       if (Lexer.is(AsmToken::EndOfStatement))
708         break;
709       
710       // FIXME: Improve diagnostic.
711       if (Lexer.isNot(AsmToken::Comma))
712         return TokError("unexpected token in directive");
713       Lexer.Lex();
714     }
715   }
716
717   Lexer.Lex();
718   return false;
719 }
720
721 /// ParseDirectiveSpace
722 ///  ::= .space expression [ , expression ]
723 bool AsmParser::ParseDirectiveSpace() {
724   int64_t NumBytes;
725   if (ParseAbsoluteExpression(NumBytes))
726     return true;
727
728   int64_t FillExpr = 0;
729   bool HasFillExpr = false;
730   if (Lexer.isNot(AsmToken::EndOfStatement)) {
731     if (Lexer.isNot(AsmToken::Comma))
732       return TokError("unexpected token in '.space' directive");
733     Lexer.Lex();
734     
735     if (ParseAbsoluteExpression(FillExpr))
736       return true;
737
738     HasFillExpr = true;
739
740     if (Lexer.isNot(AsmToken::EndOfStatement))
741       return TokError("unexpected token in '.space' directive");
742   }
743
744   Lexer.Lex();
745
746   if (NumBytes <= 0)
747     return TokError("invalid number of bytes in '.space' directive");
748
749   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
750   for (uint64_t i = 0, e = NumBytes; i != e; ++i)
751     Out.EmitValue(MCValue::get(FillExpr), 1);
752
753   return false;
754 }
755
756 /// ParseDirectiveFill
757 ///  ::= .fill expression , expression , expression
758 bool AsmParser::ParseDirectiveFill() {
759   int64_t NumValues;
760   if (ParseAbsoluteExpression(NumValues))
761     return true;
762
763   if (Lexer.isNot(AsmToken::Comma))
764     return TokError("unexpected token in '.fill' directive");
765   Lexer.Lex();
766   
767   int64_t FillSize;
768   if (ParseAbsoluteExpression(FillSize))
769     return true;
770
771   if (Lexer.isNot(AsmToken::Comma))
772     return TokError("unexpected token in '.fill' directive");
773   Lexer.Lex();
774   
775   int64_t FillExpr;
776   if (ParseAbsoluteExpression(FillExpr))
777     return true;
778
779   if (Lexer.isNot(AsmToken::EndOfStatement))
780     return TokError("unexpected token in '.fill' directive");
781   
782   Lexer.Lex();
783
784   if (FillSize != 1 && FillSize != 2 && FillSize != 4)
785     return TokError("invalid '.fill' size, expected 1, 2, or 4");
786
787   for (uint64_t i = 0, e = NumValues; i != e; ++i)
788     Out.EmitValue(MCValue::get(FillExpr), FillSize);
789
790   return false;
791 }
792
793 /// ParseDirectiveOrg
794 ///  ::= .org expression [ , expression ]
795 bool AsmParser::ParseDirectiveOrg() {
796   MCValue Offset;
797   if (ParseRelocatableExpression(Offset))
798     return true;
799
800   // Parse optional fill expression.
801   int64_t FillExpr = 0;
802   if (Lexer.isNot(AsmToken::EndOfStatement)) {
803     if (Lexer.isNot(AsmToken::Comma))
804       return TokError("unexpected token in '.org' directive");
805     Lexer.Lex();
806     
807     if (ParseAbsoluteExpression(FillExpr))
808       return true;
809
810     if (Lexer.isNot(AsmToken::EndOfStatement))
811       return TokError("unexpected token in '.org' directive");
812   }
813
814   Lexer.Lex();
815
816   // FIXME: Only limited forms of relocatable expressions are accepted here, it
817   // has to be relative to the current section.
818   Out.EmitValueToOffset(Offset, FillExpr);
819
820   return false;
821 }
822
823 /// ParseDirectiveAlign
824 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
825 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
826   int64_t Alignment;
827   if (ParseAbsoluteExpression(Alignment))
828     return true;
829
830   SMLoc MaxBytesLoc;
831   bool HasFillExpr = false;
832   int64_t FillExpr = 0;
833   int64_t MaxBytesToFill = 0;
834   if (Lexer.isNot(AsmToken::EndOfStatement)) {
835     if (Lexer.isNot(AsmToken::Comma))
836       return TokError("unexpected token in directive");
837     Lexer.Lex();
838
839     // The fill expression can be omitted while specifying a maximum number of
840     // alignment bytes, e.g:
841     //  .align 3,,4
842     if (Lexer.isNot(AsmToken::Comma)) {
843       HasFillExpr = true;
844       if (ParseAbsoluteExpression(FillExpr))
845         return true;
846     }
847
848     if (Lexer.isNot(AsmToken::EndOfStatement)) {
849       if (Lexer.isNot(AsmToken::Comma))
850         return TokError("unexpected token in directive");
851       Lexer.Lex();
852
853       MaxBytesLoc = Lexer.getLoc();
854       if (ParseAbsoluteExpression(MaxBytesToFill))
855         return true;
856       
857       if (Lexer.isNot(AsmToken::EndOfStatement))
858         return TokError("unexpected token in directive");
859     }
860   }
861
862   Lexer.Lex();
863
864   if (!HasFillExpr) {
865     // FIXME: Sometimes fill with nop.
866     FillExpr = 0;
867   }
868
869   // Compute alignment in bytes.
870   if (IsPow2) {
871     // FIXME: Diagnose overflow.
872     Alignment = 1LL << Alignment;
873   }
874
875   // Diagnose non-sensical max bytes to fill.
876   if (MaxBytesLoc.isValid()) {
877     if (MaxBytesToFill < 1) {
878       Warning(MaxBytesLoc, "alignment directive can never be satisfied in this "
879               "many bytes, ignoring");
880       return false;
881     }
882
883     if (MaxBytesToFill >= Alignment) {
884       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
885               "has no effect");
886       MaxBytesToFill = 0;
887     }
888   }
889
890   // FIXME: Target specific behavior about how the "extra" bytes are filled.
891   Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
892
893   return false;
894 }
895
896 /// ParseDirectiveSymbolAttribute
897 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
898 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
899   if (Lexer.isNot(AsmToken::EndOfStatement)) {
900     for (;;) {
901       if (Lexer.isNot(AsmToken::Identifier))
902         return TokError("expected identifier in directive");
903       
904       MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
905       Lexer.Lex();
906
907       // If this is use of an undefined symbol then mark it external.
908       if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
909         Sym->setExternal(true);
910
911       Out.EmitSymbolAttribute(Sym, Attr);
912
913       if (Lexer.is(AsmToken::EndOfStatement))
914         break;
915
916       if (Lexer.isNot(AsmToken::Comma))
917         return TokError("unexpected token in directive");
918       Lexer.Lex();
919     }
920   }
921
922   Lexer.Lex();
923   return false;  
924 }
925
926 /// ParseDirectiveDarwinSymbolDesc
927 ///  ::= .desc identifier , expression
928 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
929   if (Lexer.isNot(AsmToken::Identifier))
930     return TokError("expected identifier in directive");
931   
932   // handle the identifier as the key symbol.
933   SMLoc IDLoc = Lexer.getLoc();
934   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
935   Lexer.Lex();
936
937   if (Lexer.isNot(AsmToken::Comma))
938     return TokError("unexpected token in '.desc' directive");
939   Lexer.Lex();
940
941   SMLoc DescLoc = Lexer.getLoc();
942   int64_t DescValue;
943   if (ParseAbsoluteExpression(DescValue))
944     return true;
945
946   if (Lexer.isNot(AsmToken::EndOfStatement))
947     return TokError("unexpected token in '.desc' directive");
948   
949   Lexer.Lex();
950
951   // Set the n_desc field of this Symbol to this DescValue
952   Out.EmitSymbolDesc(Sym, DescValue);
953
954   return false;
955 }
956
957 /// ParseDirectiveComm
958 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
959 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
960   if (Lexer.isNot(AsmToken::Identifier))
961     return TokError("expected identifier in directive");
962   
963   // handle the identifier as the key symbol.
964   SMLoc IDLoc = Lexer.getLoc();
965   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
966   Lexer.Lex();
967
968   if (Lexer.isNot(AsmToken::Comma))
969     return TokError("unexpected token in directive");
970   Lexer.Lex();
971
972   int64_t Size;
973   SMLoc SizeLoc = Lexer.getLoc();
974   if (ParseAbsoluteExpression(Size))
975     return true;
976
977   int64_t Pow2Alignment = 0;
978   SMLoc Pow2AlignmentLoc;
979   if (Lexer.is(AsmToken::Comma)) {
980     Lexer.Lex();
981     Pow2AlignmentLoc = Lexer.getLoc();
982     if (ParseAbsoluteExpression(Pow2Alignment))
983       return true;
984   }
985   
986   if (Lexer.isNot(AsmToken::EndOfStatement))
987     return TokError("unexpected token in '.comm' or '.lcomm' directive");
988   
989   Lexer.Lex();
990
991   // NOTE: a size of zero for a .comm should create a undefined symbol
992   // but a size of .lcomm creates a bss symbol of size zero.
993   if (Size < 0)
994     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
995                  "be less than zero");
996
997   // NOTE: The alignment in the directive is a power of 2 value, the assember
998   // may internally end up wanting an alignment in bytes.
999   // FIXME: Diagnose overflow.
1000   if (Pow2Alignment < 0)
1001     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1002                  "alignment, can't be less than zero");
1003
1004   // TODO: Symbol must be undefined or it is a error to re-defined the symbol
1005   if (Sym->getSection() || Ctx.GetSymbolValue(Sym))
1006     return Error(IDLoc, "invalid symbol redefinition");
1007
1008   // Create the Symbol as a common or local common with Size and Pow2Alignment
1009   Out.EmitCommonSymbol(Sym, Size, Pow2Alignment, IsLocal);
1010
1011   return false;
1012 }
1013
1014 /// ParseDirectiveDarwinZerofill
1015 ///  ::= .zerofill segname , sectname [, identifier , size_expression [
1016 ///      , align_expression ]]
1017 bool AsmParser::ParseDirectiveDarwinZerofill() {
1018   if (Lexer.isNot(AsmToken::Identifier))
1019     return TokError("expected segment name after '.zerofill' directive");
1020   std::string Section = Lexer.getTok().getString();
1021   Lexer.Lex();
1022
1023   if (Lexer.isNot(AsmToken::Comma))
1024     return TokError("unexpected token in directive");
1025   Section += ',';
1026   Lexer.Lex();
1027  
1028   if (Lexer.isNot(AsmToken::Identifier))
1029     return TokError("expected section name after comma in '.zerofill' "
1030                     "directive");
1031   Section += Lexer.getTok().getString().str();
1032   Lexer.Lex();
1033
1034   // FIXME: we will need to tell GetSection() that this is to be created with or
1035   // must have the Mach-O section type of S_ZEROFILL.  Something like the code
1036   // below could be done but for now it is not as EmitZerofill() does not know
1037   // how to deal with a section type in the section name like
1038   // ParseDirectiveDarwinSection() allows.
1039   // Section += ',';
1040   // Section += "zerofill";
1041
1042   // If this is the end of the line all that was wanted was to create the
1043   // the section but with no symbol.
1044   if (Lexer.is(AsmToken::EndOfStatement)) {
1045     // Create the zerofill section but no symbol
1046     Out.EmitZerofill(Ctx.GetSection(Section.c_str()));
1047     return false;
1048   }
1049
1050   if (Lexer.isNot(AsmToken::Comma))
1051     return TokError("unexpected token in directive");
1052   Lexer.Lex();
1053
1054   if (Lexer.isNot(AsmToken::Identifier))
1055     return TokError("expected identifier in directive");
1056   
1057   // handle the identifier as the key symbol.
1058   SMLoc IDLoc = Lexer.getLoc();
1059   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
1060   Lexer.Lex();
1061
1062   if (Lexer.isNot(AsmToken::Comma))
1063     return TokError("unexpected token in directive");
1064   Lexer.Lex();
1065
1066   int64_t Size;
1067   SMLoc SizeLoc = Lexer.getLoc();
1068   if (ParseAbsoluteExpression(Size))
1069     return true;
1070
1071   int64_t Pow2Alignment = 0;
1072   SMLoc Pow2AlignmentLoc;
1073   if (Lexer.is(AsmToken::Comma)) {
1074     Lexer.Lex();
1075     Pow2AlignmentLoc = Lexer.getLoc();
1076     if (ParseAbsoluteExpression(Pow2Alignment))
1077       return true;
1078   }
1079   
1080   if (Lexer.isNot(AsmToken::EndOfStatement))
1081     return TokError("unexpected token in '.zerofill' directive");
1082   
1083   Lexer.Lex();
1084
1085   if (Size < 0)
1086     return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1087                  "than zero");
1088
1089   // NOTE: The alignment in the directive is a power of 2 value, the assember
1090   // may internally end up wanting an alignment in bytes.
1091   // FIXME: Diagnose overflow.
1092   if (Pow2Alignment < 0)
1093     return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1094                  "can't be less than zero");
1095
1096   // TODO: Symbol must be undefined or it is a error to re-defined the symbol
1097   if (Sym->getSection() || Ctx.GetSymbolValue(Sym))
1098     return Error(IDLoc, "invalid symbol redefinition");
1099
1100   // Create the zerofill Symbol with Size and Pow2Alignment
1101   Out.EmitZerofill(Ctx.GetSection(Section.c_str()), Sym, Size, Pow2Alignment);
1102
1103   return false;
1104 }
1105
1106 /// ParseDirectiveDarwinSubsectionsViaSymbols
1107 ///  ::= .subsections_via_symbols
1108 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1109   if (Lexer.isNot(AsmToken::EndOfStatement))
1110     return TokError("unexpected token in '.subsections_via_symbols' directive");
1111   
1112   Lexer.Lex();
1113
1114   Out.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1115
1116   return false;
1117 }
1118
1119 /// ParseDirectiveAbort
1120 ///  ::= .abort [ "abort_string" ]
1121 bool AsmParser::ParseDirectiveAbort() {
1122   // FIXME: Use loc from directive.
1123   SMLoc Loc = Lexer.getLoc();
1124
1125   StringRef Str = "";
1126   if (Lexer.isNot(AsmToken::EndOfStatement)) {
1127     if (Lexer.isNot(AsmToken::String))
1128       return TokError("expected string in '.abort' directive");
1129     
1130     Str = Lexer.getTok().getString();
1131
1132     Lexer.Lex();
1133   }
1134
1135   if (Lexer.isNot(AsmToken::EndOfStatement))
1136     return TokError("unexpected token in '.abort' directive");
1137   
1138   Lexer.Lex();
1139
1140   // FIXME: Handle here.
1141   if (Str.empty())
1142     Error(Loc, ".abort detected. Assembly stopping.");
1143   else
1144     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1145
1146   return false;
1147 }
1148
1149 /// ParseDirectiveLsym
1150 ///  ::= .lsym identifier , expression
1151 bool AsmParser::ParseDirectiveDarwinLsym() {
1152   if (Lexer.isNot(AsmToken::Identifier))
1153     return TokError("expected identifier in directive");
1154   
1155   // handle the identifier as the key symbol.
1156   SMLoc IDLoc = Lexer.getLoc();
1157   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
1158   Lexer.Lex();
1159
1160   if (Lexer.isNot(AsmToken::Comma))
1161     return TokError("unexpected token in '.lsym' directive");
1162   Lexer.Lex();
1163
1164   MCValue Expr;
1165   if (ParseRelocatableExpression(Expr))
1166     return true;
1167
1168   if (Lexer.isNot(AsmToken::EndOfStatement))
1169     return TokError("unexpected token in '.lsym' directive");
1170   
1171   Lexer.Lex();
1172
1173   // Create the Sym with the value of the Expr
1174   Out.EmitLocalSymbol(Sym, Expr);
1175
1176   return false;
1177 }
1178
1179 /// ParseDirectiveInclude
1180 ///  ::= .include "filename"
1181 bool AsmParser::ParseDirectiveInclude() {
1182   if (Lexer.isNot(AsmToken::String))
1183     return TokError("expected string in '.include' directive");
1184   
1185   std::string Filename = Lexer.getTok().getString();
1186   SMLoc IncludeLoc = Lexer.getLoc();
1187   Lexer.Lex();
1188
1189   if (Lexer.isNot(AsmToken::EndOfStatement))
1190     return TokError("unexpected token in '.include' directive");
1191   
1192   // Strip the quotes.
1193   Filename = Filename.substr(1, Filename.size()-2);
1194   
1195   // Attempt to switch the lexer to the included file before consuming the end
1196   // of statement to avoid losing it when we switch.
1197   if (Lexer.EnterIncludeFile(Filename)) {
1198     Lexer.PrintMessage(IncludeLoc,
1199                        "Could not find include file '" + Filename + "'",
1200                        "error");
1201     return true;
1202   }
1203
1204   return false;
1205 }
1206
1207 /// ParseDirectiveDarwinDumpOrLoad
1208 ///  ::= ( .dump | .load ) "filename"
1209 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1210   if (Lexer.isNot(AsmToken::String))
1211     return TokError("expected string in '.dump' or '.load' directive");
1212   
1213   Lexer.Lex();
1214
1215   if (Lexer.isNot(AsmToken::EndOfStatement))
1216     return TokError("unexpected token in '.dump' or '.load' directive");
1217   
1218   Lexer.Lex();
1219
1220   // FIXME: If/when .dump and .load are implemented they will be done in the
1221   // the assembly parser and not have any need for an MCStreamer API.
1222   if (IsDump)
1223     Warning(IDLoc, "ignoring directive .dump for now");
1224   else
1225     Warning(IDLoc, "ignoring directive .load for now");
1226
1227   return false;
1228 }