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