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