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