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