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