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