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