MC-COFF: Add COFFAsmParser. Completes PR8343.
[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/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 Twine &Msg, const char *Type) const {
152     SrcMgr.PrintMessage(Loc, Msg, Type);
153   }
154
155   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
156   bool EnterIncludeFile(const std::string &Filename);
157
158   /// \brief Reset the current lexer position to that given by \arg Loc. The
159   /// current token is not set; clients should ensure Lex() is called
160   /// subsequently.
161   void JumpToLoc(SMLoc Loc);
162
163   void EatToEndOfStatement();
164
165   /// \brief Parse up to the end of statement and a return the contents from the
166   /// current token until the end of the statement; the current token on exit
167   /// will be either the EndOfStatement or EOF.
168   StringRef ParseStringToEndOfStatement();
169
170   bool ParseAssignment(StringRef Name);
171
172   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
173   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
174   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
175
176   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
177   /// and set \arg Res to the identifier contents.
178   bool ParseIdentifier(StringRef &Res);
179
180   // Directive Parsing.
181   bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
182   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
183   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
184   bool ParseDirectiveFill(); // ".fill"
185   bool ParseDirectiveSpace(); // ".space"
186   bool ParseDirectiveZero(); // ".zero"
187   bool ParseDirectiveSet(); // ".set"
188   bool ParseDirectiveOrg(); // ".org"
189   // ".align{,32}", ".p2align{,w,l}"
190   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
191
192   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
193   /// accepts a single symbol (which should be a label or an external).
194   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
195   bool ParseDirectiveELFType(); // ELF specific ".type"
196
197   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
198
199   bool ParseDirectiveAbort(); // ".abort"
200   bool ParseDirectiveInclude(); // ".include"
201
202   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
203   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
204   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
205   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
206
207   /// ParseEscapedString - Parse the current token as a string which may include
208   /// escaped characters and return the string contents.
209   bool ParseEscapedString(std::string &Data);
210
211   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
212                                     MCSymbolRefExpr::VariantKind Variant);
213 };
214
215 /// \brief Generic implementations of directive handling, etc. which is shared
216 /// (or the default, at least) for all assembler parser.
217 class GenericAsmParser : public MCAsmParserExtension {
218   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
219   void AddDirectiveHandler(StringRef Directive) {
220     getParser().AddDirectiveHandler(this, Directive,
221                                     HandleDirective<GenericAsmParser, Handler>);
222   }
223
224 public:
225   GenericAsmParser() {}
226
227   AsmParser &getParser() {
228     return (AsmParser&) this->MCAsmParserExtension::getParser();
229   }
230
231   virtual void Initialize(MCAsmParser &Parser) {
232     // Call the base implementation.
233     this->MCAsmParserExtension::Initialize(Parser);
234
235     // Debugging directives.
236     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
237     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
238     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
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
257   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
258   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
259   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
260
261   void ParseUleb128(uint64_t Value);
262   void ParseSleb128(int64_t Value);
263   bool ParseDirectiveLEB128(StringRef, SMLoc);
264 };
265
266 }
267
268 namespace llvm {
269
270 extern MCAsmParserExtension *createDarwinAsmParser();
271 extern MCAsmParserExtension *createELFAsmParser();
272 extern MCAsmParserExtension *createCOFFAsmParser();
273
274 }
275
276 enum { DEFAULT_ADDRSPACE = 0 };
277
278 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
279                      MCStreamer &_Out, const MCAsmInfo &_MAI)
280   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
281     GenericParser(new GenericAsmParser), PlatformParser(0),
282     CurBuffer(0), MacrosEnabled(true) {
283   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
284
285   // Initialize the generic parser.
286   GenericParser->Initialize(*this);
287
288   // Initialize the platform / file format parser.
289   //
290   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
291   // created.
292   if (_MAI.hasMicrosoftFastStdCallMangling()) {
293     PlatformParser = createCOFFAsmParser();
294     PlatformParser->Initialize(*this);
295   } else if (_MAI.hasSubsectionsViaSymbols()) {
296     PlatformParser = createDarwinAsmParser();
297     PlatformParser->Initialize(*this);
298   } else {
299     PlatformParser = createELFAsmParser();
300     PlatformParser->Initialize(*this);
301   }
302 }
303
304 AsmParser::~AsmParser() {
305   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
306
307   // Destroy any macros.
308   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
309          ie = MacroMap.end(); it != ie; ++it)
310     delete it->getValue();
311
312   delete PlatformParser;
313   delete GenericParser;
314 }
315
316 void AsmParser::PrintMacroInstantiations() {
317   // Print the active macro instantiation stack.
318   for (std::vector<MacroInstantiation*>::const_reverse_iterator
319          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
320     PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
321                  "note");
322 }
323
324 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
325   PrintMessage(L, Msg, "warning");
326   PrintMacroInstantiations();
327 }
328
329 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
330   HadError = true;
331   PrintMessage(L, Msg, "error");
332   PrintMacroInstantiations();
333   return true;
334 }
335
336 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
337   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
338   if (NewBuf == -1)
339     return true;
340
341   CurBuffer = NewBuf;
342
343   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
344
345   return false;
346 }
347
348 void AsmParser::JumpToLoc(SMLoc Loc) {
349   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
350   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
351 }
352
353 const AsmToken &AsmParser::Lex() {
354   const AsmToken *tok = &Lexer.Lex();
355
356   if (tok->is(AsmToken::Eof)) {
357     // If this is the end of an included file, pop the parent file off the
358     // include stack.
359     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
360     if (ParentIncludeLoc != SMLoc()) {
361       JumpToLoc(ParentIncludeLoc);
362       tok = &Lexer.Lex();
363     }
364   }
365
366   if (tok->is(AsmToken::Error))
367     Error(Lexer.getErrLoc(), Lexer.getErr());
368
369   return *tok;
370 }
371
372 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
373   // Create the initial section, if requested.
374   if (!NoInitialTextSection)
375     Out.InitSections();
376
377   // Prime the lexer.
378   Lex();
379
380   HadError = false;
381   AsmCond StartingCondState = TheCondState;
382
383   // While we have input, parse each statement.
384   while (Lexer.isNot(AsmToken::Eof)) {
385     if (!ParseStatement()) continue;
386
387     // We had an error, validate that one was emitted and recover by skipping to
388     // the next line.
389     assert(HadError && "Parse statement returned an error, but none emitted!");
390     EatToEndOfStatement();
391   }
392
393   if (TheCondState.TheCond != StartingCondState.TheCond ||
394       TheCondState.Ignore != StartingCondState.Ignore)
395     return TokError("unmatched .ifs or .elses");
396
397   // Check to see there are no empty DwarfFile slots.
398   const std::vector<MCDwarfFile *> &MCDwarfFiles =
399     getContext().getMCDwarfFiles();
400   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
401     if (!MCDwarfFiles[i])
402       TokError("unassigned file number: " + Twine(i) + " for .file directives");
403   }
404
405   // Finalize the output stream if there are no errors and if the client wants
406   // us to.
407   if (!HadError && !NoFinalize)
408     Out.Finish();
409
410   return HadError;
411 }
412
413 void AsmParser::CheckForValidSection() {
414   if (!getStreamer().getCurrentSection()) {
415     TokError("expected section directive before assembly directive");
416     Out.SwitchSection(Ctx.getMachOSection(
417                         "__TEXT", "__text",
418                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
419                         0, SectionKind::getText()));
420   }
421 }
422
423 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
424 void AsmParser::EatToEndOfStatement() {
425   while (Lexer.isNot(AsmToken::EndOfStatement) &&
426          Lexer.isNot(AsmToken::Eof))
427     Lex();
428
429   // Eat EOL.
430   if (Lexer.is(AsmToken::EndOfStatement))
431     Lex();
432 }
433
434 StringRef AsmParser::ParseStringToEndOfStatement() {
435   const char *Start = getTok().getLoc().getPointer();
436
437   while (Lexer.isNot(AsmToken::EndOfStatement) &&
438          Lexer.isNot(AsmToken::Eof))
439     Lex();
440
441   const char *End = getTok().getLoc().getPointer();
442   return StringRef(Start, End - Start);
443 }
444
445 /// ParseParenExpr - Parse a paren expression and return it.
446 /// NOTE: This assumes the leading '(' has already been consumed.
447 ///
448 /// parenexpr ::= expr)
449 ///
450 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
451   if (ParseExpression(Res)) return true;
452   if (Lexer.isNot(AsmToken::RParen))
453     return TokError("expected ')' in parentheses expression");
454   EndLoc = Lexer.getLoc();
455   Lex();
456   return false;
457 }
458
459 /// ParsePrimaryExpr - Parse a primary expression and return it.
460 ///  primaryexpr ::= (parenexpr
461 ///  primaryexpr ::= symbol
462 ///  primaryexpr ::= number
463 ///  primaryexpr ::= '.'
464 ///  primaryexpr ::= ~,+,- primaryexpr
465 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
466   switch (Lexer.getKind()) {
467   default:
468     return TokError("unknown token in expression");
469   case AsmToken::Exclaim:
470     Lex(); // Eat the operator.
471     if (ParsePrimaryExpr(Res, EndLoc))
472       return true;
473     Res = MCUnaryExpr::CreateLNot(Res, getContext());
474     return false;
475   case AsmToken::Dollar:
476   case AsmToken::String:
477   case AsmToken::Identifier: {
478     EndLoc = Lexer.getLoc();
479
480     StringRef Identifier;
481     if (ParseIdentifier(Identifier))
482       return false;
483
484     // This is a symbol reference.
485     std::pair<StringRef, StringRef> Split = Identifier.split('@');
486     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
487
488     // Mark the symbol as used in an expression.
489     Sym->setUsedInExpr(true);
490
491     // Lookup the symbol variant if used.
492     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
493     if (Split.first.size() != Identifier.size()) {
494       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
495       if (Variant == MCSymbolRefExpr::VK_Invalid) {
496         Variant = MCSymbolRefExpr::VK_None;
497         TokError("invalid variant '" + Split.second + "'");
498       }
499     }
500
501     // If this is an absolute variable reference, substitute it now to preserve
502     // semantics in the face of reassignment.
503     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
504       if (Variant)
505         return Error(EndLoc, "unexpected modified on variable reference");
506
507       Res = Sym->getVariableValue();
508       return false;
509     }
510
511     // Otherwise create a symbol ref.
512     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
513     return false;
514   }
515   case AsmToken::Integer: {
516     SMLoc Loc = getTok().getLoc();
517     int64_t IntVal = getTok().getIntVal();
518     Res = MCConstantExpr::Create(IntVal, getContext());
519     EndLoc = Lexer.getLoc();
520     Lex(); // Eat token.
521     // Look for 'b' or 'f' following an Integer as a directional label
522     if (Lexer.getKind() == AsmToken::Identifier) {
523       StringRef IDVal = getTok().getString();
524       if (IDVal == "f" || IDVal == "b"){
525         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
526                                                       IDVal == "f" ? 1 : 0);
527         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
528                                       getContext());
529         if(IDVal == "b" && Sym->isUndefined())
530           return Error(Loc, "invalid reference to undefined symbol");
531         EndLoc = Lexer.getLoc();
532         Lex(); // Eat identifier.
533       }
534     }
535     return false;
536   }
537   case AsmToken::Dot: {
538     // This is a '.' reference, which references the current PC.  Emit a
539     // temporary label to the streamer and refer to it.
540     MCSymbol *Sym = Ctx.CreateTempSymbol();
541     Out.EmitLabel(Sym);
542     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
543     EndLoc = Lexer.getLoc();
544     Lex(); // Eat identifier.
545     return false;
546   }
547
548   case AsmToken::LParen:
549     Lex(); // Eat the '('.
550     return ParseParenExpr(Res, EndLoc);
551   case AsmToken::Minus:
552     Lex(); // Eat the operator.
553     if (ParsePrimaryExpr(Res, EndLoc))
554       return true;
555     Res = MCUnaryExpr::CreateMinus(Res, getContext());
556     return false;
557   case AsmToken::Plus:
558     Lex(); // Eat the operator.
559     if (ParsePrimaryExpr(Res, EndLoc))
560       return true;
561     Res = MCUnaryExpr::CreatePlus(Res, getContext());
562     return false;
563   case AsmToken::Tilde:
564     Lex(); // Eat the operator.
565     if (ParsePrimaryExpr(Res, EndLoc))
566       return true;
567     Res = MCUnaryExpr::CreateNot(Res, getContext());
568     return false;
569   }
570 }
571
572 bool AsmParser::ParseExpression(const MCExpr *&Res) {
573   SMLoc EndLoc;
574   return ParseExpression(Res, EndLoc);
575 }
576
577 const MCExpr *
578 AsmParser::ApplyModifierToExpr(const MCExpr *E,
579                                MCSymbolRefExpr::VariantKind Variant) {
580   // Recurse over the given expression, rebuilding it to apply the given variant
581   // if there is exactly one symbol.
582   switch (E->getKind()) {
583   case MCExpr::Target:
584   case MCExpr::Constant:
585     return 0;
586
587   case MCExpr::SymbolRef: {
588     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
589
590     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
591       TokError("invalid variant on expression '" +
592                getTok().getIdentifier() + "' (already modified)");
593       return E;
594     }
595
596     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
597   }
598
599   case MCExpr::Unary: {
600     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
601     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
602     if (!Sub)
603       return 0;
604     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
605   }
606
607   case MCExpr::Binary: {
608     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
609     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
610     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
611
612     if (!LHS && !RHS)
613       return 0;
614
615     if (!LHS) LHS = BE->getLHS();
616     if (!RHS) RHS = BE->getRHS();
617
618     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
619   }
620   }
621
622   assert(0 && "Invalid expression kind!");
623   return 0;
624 }
625
626 /// ParseExpression - Parse an expression and return it.
627 ///
628 ///  expr ::= expr +,- expr          -> lowest.
629 ///  expr ::= expr |,^,&,! expr      -> middle.
630 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
631 ///  expr ::= primaryexpr
632 ///
633 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
634   // Parse the expression.
635   Res = 0;
636   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
637     return true;
638
639   // As a special case, we support 'a op b @ modifier' by rewriting the
640   // expression to include the modifier. This is inefficient, but in general we
641   // expect users to use 'a@modifier op b'.
642   if (Lexer.getKind() == AsmToken::At) {
643     Lex();
644
645     if (Lexer.isNot(AsmToken::Identifier))
646       return TokError("unexpected symbol modifier following '@'");
647
648     MCSymbolRefExpr::VariantKind Variant =
649       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
650     if (Variant == MCSymbolRefExpr::VK_Invalid)
651       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
652
653     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
654     if (!ModifiedRes) {
655       return TokError("invalid modifier '" + getTok().getIdentifier() +
656                       "' (no symbols present)");
657       return true;
658     }
659
660     Res = ModifiedRes;
661     Lex();
662   }
663
664   // Try to constant fold it up front, if possible.
665   int64_t Value;
666   if (Res->EvaluateAsAbsolute(Value))
667     Res = MCConstantExpr::Create(Value, getContext());
668
669   return false;
670 }
671
672 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
673   Res = 0;
674   return ParseParenExpr(Res, EndLoc) ||
675          ParseBinOpRHS(1, Res, EndLoc);
676 }
677
678 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
679   const MCExpr *Expr;
680
681   SMLoc StartLoc = Lexer.getLoc();
682   if (ParseExpression(Expr))
683     return true;
684
685   if (!Expr->EvaluateAsAbsolute(Res))
686     return Error(StartLoc, "expected absolute expression");
687
688   return false;
689 }
690
691 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
692                                    MCBinaryExpr::Opcode &Kind) {
693   switch (K) {
694   default:
695     return 0;    // not a binop.
696
697     // Lowest Precedence: &&, ||, @
698   case AsmToken::AmpAmp:
699     Kind = MCBinaryExpr::LAnd;
700     return 1;
701   case AsmToken::PipePipe:
702     Kind = MCBinaryExpr::LOr;
703     return 1;
704
705
706     // Low Precedence: |, &, ^
707     //
708     // FIXME: gas seems to support '!' as an infix operator?
709   case AsmToken::Pipe:
710     Kind = MCBinaryExpr::Or;
711     return 2;
712   case AsmToken::Caret:
713     Kind = MCBinaryExpr::Xor;
714     return 2;
715   case AsmToken::Amp:
716     Kind = MCBinaryExpr::And;
717     return 2;
718
719     // Intermediate Precedence: +, -, ==, !=, <>, <, <=, >, >=
720   case AsmToken::Plus:
721     Kind = MCBinaryExpr::Add;
722     return 3;
723   case AsmToken::Minus:
724     Kind = MCBinaryExpr::Sub;
725     return 3;
726   case AsmToken::EqualEqual:
727     Kind = MCBinaryExpr::EQ;
728     return 3;
729   case AsmToken::ExclaimEqual:
730   case AsmToken::LessGreater:
731     Kind = MCBinaryExpr::NE;
732     return 3;
733   case AsmToken::Less:
734     Kind = MCBinaryExpr::LT;
735     return 3;
736   case AsmToken::LessEqual:
737     Kind = MCBinaryExpr::LTE;
738     return 3;
739   case AsmToken::Greater:
740     Kind = MCBinaryExpr::GT;
741     return 3;
742   case AsmToken::GreaterEqual:
743     Kind = MCBinaryExpr::GTE;
744     return 3;
745
746     // Highest Precedence: *, /, %, <<, >>
747   case AsmToken::Star:
748     Kind = MCBinaryExpr::Mul;
749     return 4;
750   case AsmToken::Slash:
751     Kind = MCBinaryExpr::Div;
752     return 4;
753   case AsmToken::Percent:
754     Kind = MCBinaryExpr::Mod;
755     return 4;
756   case AsmToken::LessLess:
757     Kind = MCBinaryExpr::Shl;
758     return 4;
759   case AsmToken::GreaterGreater:
760     Kind = MCBinaryExpr::Shr;
761     return 4;
762   }
763 }
764
765
766 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
767 /// Res contains the LHS of the expression on input.
768 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
769                               SMLoc &EndLoc) {
770   while (1) {
771     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
772     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
773
774     // If the next token is lower precedence than we are allowed to eat, return
775     // successfully with what we ate already.
776     if (TokPrec < Precedence)
777       return false;
778
779     Lex();
780
781     // Eat the next primary expression.
782     const MCExpr *RHS;
783     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
784
785     // If BinOp binds less tightly with RHS than the operator after RHS, let
786     // the pending operator take RHS as its LHS.
787     MCBinaryExpr::Opcode Dummy;
788     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
789     if (TokPrec < NextTokPrec) {
790       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
791     }
792
793     // Merge LHS and RHS according to operator.
794     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
795   }
796 }
797
798
799
800
801 /// ParseStatement:
802 ///   ::= EndOfStatement
803 ///   ::= Label* Directive ...Operands... EndOfStatement
804 ///   ::= Label* Identifier OperandList* EndOfStatement
805 bool AsmParser::ParseStatement() {
806   if (Lexer.is(AsmToken::EndOfStatement)) {
807     Out.AddBlankLine();
808     Lex();
809     return false;
810   }
811
812   // Statements always start with an identifier.
813   AsmToken ID = getTok();
814   SMLoc IDLoc = ID.getLoc();
815   StringRef IDVal;
816   int64_t LocalLabelVal = -1;
817   // GUESS allow an integer followed by a ':' as a directional local label
818   if (Lexer.is(AsmToken::Integer)) {
819     LocalLabelVal = getTok().getIntVal();
820     if (LocalLabelVal < 0) {
821       if (!TheCondState.Ignore)
822         return TokError("unexpected token at start of statement");
823       IDVal = "";
824     }
825     else {
826       IDVal = getTok().getString();
827       Lex(); // Consume the integer token to be used as an identifier token.
828       if (Lexer.getKind() != AsmToken::Colon) {
829         if (!TheCondState.Ignore)
830           return TokError("unexpected token at start of statement");
831       }
832     }
833   }
834   else if (ParseIdentifier(IDVal)) {
835     if (!TheCondState.Ignore)
836       return TokError("unexpected token at start of statement");
837     IDVal = "";
838   }
839
840   // Handle conditional assembly here before checking for skipping.  We
841   // have to do this so that .endif isn't skipped in a ".if 0" block for
842   // example.
843   if (IDVal == ".if")
844     return ParseDirectiveIf(IDLoc);
845   if (IDVal == ".elseif")
846     return ParseDirectiveElseIf(IDLoc);
847   if (IDVal == ".else")
848     return ParseDirectiveElse(IDLoc);
849   if (IDVal == ".endif")
850     return ParseDirectiveEndIf(IDLoc);
851
852   // If we are in a ".if 0" block, ignore this statement.
853   if (TheCondState.Ignore) {
854     EatToEndOfStatement();
855     return false;
856   }
857
858   // FIXME: Recurse on local labels?
859
860   // See what kind of statement we have.
861   switch (Lexer.getKind()) {
862   case AsmToken::Colon: {
863     CheckForValidSection();
864
865     // identifier ':'   -> Label.
866     Lex();
867
868     // Diagnose attempt to use a variable as a label.
869     //
870     // FIXME: Diagnostics. Note the location of the definition as a label.
871     // FIXME: This doesn't diagnose assignment to a symbol which has been
872     // implicitly marked as external.
873     MCSymbol *Sym;
874     if (LocalLabelVal == -1)
875       Sym = getContext().GetOrCreateSymbol(IDVal);
876     else
877       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
878     if (!Sym->isUndefined() || Sym->isVariable())
879       return Error(IDLoc, "invalid symbol redefinition");
880
881     // Emit the label.
882     Out.EmitLabel(Sym);
883
884     // Consume any end of statement token, if present, to avoid spurious
885     // AddBlankLine calls().
886     if (Lexer.is(AsmToken::EndOfStatement)) {
887       Lex();
888       if (Lexer.is(AsmToken::Eof))
889         return false;
890     }
891
892     return ParseStatement();
893   }
894
895   case AsmToken::Equal:
896     // identifier '=' ... -> assignment statement
897     Lex();
898
899     return ParseAssignment(IDVal);
900
901   default: // Normal instruction or directive.
902     break;
903   }
904
905   // If macros are enabled, check to see if this is a macro instantiation.
906   if (MacrosEnabled)
907     if (const Macro *M = MacroMap.lookup(IDVal))
908       return HandleMacroEntry(IDVal, IDLoc, M);
909
910   // Otherwise, we have a normal instruction or directive.
911   if (IDVal[0] == '.') {
912     // Assembler features
913     if (IDVal == ".set")
914       return ParseDirectiveSet();
915
916     // Data directives
917
918     if (IDVal == ".ascii")
919       return ParseDirectiveAscii(false);
920     if (IDVal == ".asciz")
921       return ParseDirectiveAscii(true);
922
923     if (IDVal == ".byte")
924       return ParseDirectiveValue(1);
925     if (IDVal == ".short")
926       return ParseDirectiveValue(2);
927     if (IDVal == ".long")
928       return ParseDirectiveValue(4);
929     if (IDVal == ".quad")
930       return ParseDirectiveValue(8);
931     if (IDVal == ".single")
932       return ParseDirectiveRealValue(APFloat::IEEEsingle);
933     if (IDVal == ".double")
934       return ParseDirectiveRealValue(APFloat::IEEEdouble);
935
936     if (IDVal == ".align") {
937       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
938       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
939     }
940     if (IDVal == ".align32") {
941       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
942       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
943     }
944     if (IDVal == ".balign")
945       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
946     if (IDVal == ".balignw")
947       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
948     if (IDVal == ".balignl")
949       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
950     if (IDVal == ".p2align")
951       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
952     if (IDVal == ".p2alignw")
953       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
954     if (IDVal == ".p2alignl")
955       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
956
957     if (IDVal == ".org")
958       return ParseDirectiveOrg();
959
960     if (IDVal == ".fill")
961       return ParseDirectiveFill();
962     if (IDVal == ".space")
963       return ParseDirectiveSpace();
964     if (IDVal == ".zero")
965       return ParseDirectiveZero();
966
967     // Symbol attribute directives
968
969     if (IDVal == ".globl" || IDVal == ".global")
970       return ParseDirectiveSymbolAttribute(MCSA_Global);
971     // ELF only? Should it be here?
972     if (IDVal == ".local")
973       return ParseDirectiveSymbolAttribute(MCSA_Local);
974     if (IDVal == ".hidden")
975       return ParseDirectiveSymbolAttribute(MCSA_Hidden);
976     if (IDVal == ".indirect_symbol")
977       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
978     if (IDVal == ".internal")
979       return ParseDirectiveSymbolAttribute(MCSA_Internal);
980     if (IDVal == ".lazy_reference")
981       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
982     if (IDVal == ".no_dead_strip")
983       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
984     if (IDVal == ".private_extern")
985       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
986     if (IDVal == ".protected")
987       return ParseDirectiveSymbolAttribute(MCSA_Protected);
988     if (IDVal == ".reference")
989       return ParseDirectiveSymbolAttribute(MCSA_Reference);
990     if (IDVal == ".weak")
991       return ParseDirectiveSymbolAttribute(MCSA_Weak);
992     if (IDVal == ".weak_definition")
993       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
994     if (IDVal == ".weak_reference")
995       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
996     if (IDVal == ".weak_def_can_be_hidden")
997       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
998
999     if (IDVal == ".comm")
1000       return ParseDirectiveComm(/*IsLocal=*/false);
1001     if (IDVal == ".lcomm")
1002       return ParseDirectiveComm(/*IsLocal=*/true);
1003
1004     if (IDVal == ".abort")
1005       return ParseDirectiveAbort();
1006     if (IDVal == ".include")
1007       return ParseDirectiveInclude();
1008
1009     // Look up the handler in the handler table.
1010     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1011       DirectiveMap.lookup(IDVal);
1012     if (Handler.first)
1013       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1014
1015     // Target hook for parsing target specific directives.
1016     if (!getTargetParser().ParseDirective(ID))
1017       return false;
1018
1019     Warning(IDLoc, "ignoring directive for now");
1020     EatToEndOfStatement();
1021     return false;
1022   }
1023
1024   CheckForValidSection();
1025
1026   // Canonicalize the opcode to lower case.
1027   SmallString<128> Opcode;
1028   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1029     Opcode.push_back(tolower(IDVal[i]));
1030
1031   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1032   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1033                                                      ParsedOperands);
1034
1035   // Dump the parsed representation, if requested.
1036   if (getShowParsedOperands()) {
1037     SmallString<256> Str;
1038     raw_svector_ostream OS(Str);
1039     OS << "parsed instruction: [";
1040     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1041       if (i != 0)
1042         OS << ", ";
1043       ParsedOperands[i]->dump(OS);
1044     }
1045     OS << "]";
1046
1047     PrintMessage(IDLoc, OS.str(), "note");
1048   }
1049
1050   // If parsing succeeded, match the instruction.
1051   if (!HadError)
1052     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1053                                                          Out);
1054
1055   // Free any parsed operands.
1056   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1057     delete ParsedOperands[i];
1058
1059   // Don't skip the rest of the line, the instruction parser is responsible for
1060   // that.
1061   return false;
1062 }
1063
1064 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1065                                    const std::vector<std::vector<AsmToken> > &A)
1066   : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1067 {
1068   // Macro instantiation is lexical, unfortunately. We construct a new buffer
1069   // to hold the macro body with substitutions.
1070   SmallString<256> Buf;
1071   raw_svector_ostream OS(Buf);
1072
1073   StringRef Body = M->Body;
1074   while (!Body.empty()) {
1075     // Scan for the next substitution.
1076     std::size_t End = Body.size(), Pos = 0;
1077     for (; Pos != End; ++Pos) {
1078       // Check for a substitution or escape.
1079       if (Body[Pos] != '$' || Pos + 1 == End)
1080         continue;
1081
1082       char Next = Body[Pos + 1];
1083       if (Next == '$' || Next == 'n' || isdigit(Next))
1084         break;
1085     }
1086
1087     // Add the prefix.
1088     OS << Body.slice(0, Pos);
1089
1090     // Check if we reached the end.
1091     if (Pos == End)
1092       break;
1093
1094     switch (Body[Pos+1]) {
1095        // $$ => $
1096     case '$':
1097       OS << '$';
1098       break;
1099
1100       // $n => number of arguments
1101     case 'n':
1102       OS << A.size();
1103       break;
1104
1105        // $[0-9] => argument
1106     default: {
1107       // Missing arguments are ignored.
1108       unsigned Index = Body[Pos+1] - '0';
1109       if (Index >= A.size())
1110         break;
1111
1112       // Otherwise substitute with the token values, with spaces eliminated.
1113       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1114              ie = A[Index].end(); it != ie; ++it)
1115         OS << it->getString();
1116       break;
1117     }
1118     }
1119
1120     // Update the scan point.
1121     Body = Body.substr(Pos + 2);
1122   }
1123
1124   // We include the .endmacro in the buffer as our queue to exit the macro
1125   // instantiation.
1126   OS << ".endmacro\n";
1127
1128   Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1129 }
1130
1131 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1132                                  const Macro *M) {
1133   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1134   // this, although we should protect against infinite loops.
1135   if (ActiveMacros.size() == 20)
1136     return TokError("macros cannot be nested more than 20 levels deep");
1137
1138   // Parse the macro instantiation arguments.
1139   std::vector<std::vector<AsmToken> > MacroArguments;
1140   MacroArguments.push_back(std::vector<AsmToken>());
1141   unsigned ParenLevel = 0;
1142   for (;;) {
1143     if (Lexer.is(AsmToken::Eof))
1144       return TokError("unexpected token in macro instantiation");
1145     if (Lexer.is(AsmToken::EndOfStatement))
1146       break;
1147
1148     // If we aren't inside parentheses and this is a comma, start a new token
1149     // list.
1150     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1151       MacroArguments.push_back(std::vector<AsmToken>());
1152     } else {
1153       // Adjust the current parentheses level.
1154       if (Lexer.is(AsmToken::LParen))
1155         ++ParenLevel;
1156       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1157         --ParenLevel;
1158
1159       // Append the token to the current argument list.
1160       MacroArguments.back().push_back(getTok());
1161     }
1162     Lex();
1163   }
1164
1165   // Create the macro instantiation object and add to the current macro
1166   // instantiation stack.
1167   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1168                                                   getTok().getLoc(),
1169                                                   MacroArguments);
1170   ActiveMacros.push_back(MI);
1171
1172   // Jump to the macro instantiation and prime the lexer.
1173   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1174   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1175   Lex();
1176
1177   return false;
1178 }
1179
1180 void AsmParser::HandleMacroExit() {
1181   // Jump to the EndOfStatement we should return to, and consume it.
1182   JumpToLoc(ActiveMacros.back()->ExitLoc);
1183   Lex();
1184
1185   // Pop the instantiation entry.
1186   delete ActiveMacros.back();
1187   ActiveMacros.pop_back();
1188 }
1189
1190 bool AsmParser::ParseAssignment(StringRef Name) {
1191   // FIXME: Use better location, we should use proper tokens.
1192   SMLoc EqualLoc = Lexer.getLoc();
1193
1194   const MCExpr *Value;
1195   if (ParseExpression(Value))
1196     return true;
1197
1198   if (Lexer.isNot(AsmToken::EndOfStatement))
1199     return TokError("unexpected token in assignment");
1200
1201   // Eat the end of statement marker.
1202   Lex();
1203
1204   // Validate that the LHS is allowed to be a variable (either it has not been
1205   // used as a symbol, or it is an absolute symbol).
1206   MCSymbol *Sym = getContext().LookupSymbol(Name);
1207   if (Sym) {
1208     // Diagnose assignment to a label.
1209     //
1210     // FIXME: Diagnostics. Note the location of the definition as a label.
1211     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1212     if (Sym->isUndefined() && !Sym->isUsedInExpr())
1213       ; // Allow redefinitions of undefined symbols only used in directives.
1214     else if (!Sym->isUndefined() && !Sym->isAbsolute())
1215       return Error(EqualLoc, "redefinition of '" + Name + "'");
1216     else if (!Sym->isVariable())
1217       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1218     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1219       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1220                    Name + "'");
1221   } else
1222     Sym = getContext().GetOrCreateSymbol(Name);
1223
1224   // FIXME: Handle '.'.
1225
1226   Sym->setUsedInExpr(true);
1227
1228   // Do the assignment.
1229   Out.EmitAssignment(Sym, Value);
1230
1231   return false;
1232 }
1233
1234 /// ParseIdentifier:
1235 ///   ::= identifier
1236 ///   ::= string
1237 bool AsmParser::ParseIdentifier(StringRef &Res) {
1238   // The assembler has relaxed rules for accepting identifiers, in particular we
1239   // allow things like '.globl $foo', which would normally be separate
1240   // tokens. At this level, we have already lexed so we cannot (currently)
1241   // handle this as a context dependent token, instead we detect adjacent tokens
1242   // and return the combined identifier.
1243   if (Lexer.is(AsmToken::Dollar)) {
1244     SMLoc DollarLoc = getLexer().getLoc();
1245
1246     // Consume the dollar sign, and check for a following identifier.
1247     Lex();
1248     if (Lexer.isNot(AsmToken::Identifier))
1249       return true;
1250
1251     // We have a '$' followed by an identifier, make sure they are adjacent.
1252     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1253       return true;
1254
1255     // Construct the joined identifier and consume the token.
1256     Res = StringRef(DollarLoc.getPointer(),
1257                     getTok().getIdentifier().size() + 1);
1258     Lex();
1259     return false;
1260   }
1261
1262   if (Lexer.isNot(AsmToken::Identifier) &&
1263       Lexer.isNot(AsmToken::String))
1264     return true;
1265
1266   Res = getTok().getIdentifier();
1267
1268   Lex(); // Consume the identifier token.
1269
1270   return false;
1271 }
1272
1273 /// ParseDirectiveSet:
1274 ///   ::= .set identifier ',' expression
1275 bool AsmParser::ParseDirectiveSet() {
1276   StringRef Name;
1277
1278   if (ParseIdentifier(Name))
1279     return TokError("expected identifier after '.set' directive");
1280
1281   if (getLexer().isNot(AsmToken::Comma))
1282     return TokError("unexpected token in '.set'");
1283   Lex();
1284
1285   return ParseAssignment(Name);
1286 }
1287
1288 bool AsmParser::ParseEscapedString(std::string &Data) {
1289   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1290
1291   Data = "";
1292   StringRef Str = getTok().getStringContents();
1293   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1294     if (Str[i] != '\\') {
1295       Data += Str[i];
1296       continue;
1297     }
1298
1299     // Recognize escaped characters. Note that this escape semantics currently
1300     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1301     ++i;
1302     if (i == e)
1303       return TokError("unexpected backslash at end of string");
1304
1305     // Recognize octal sequences.
1306     if ((unsigned) (Str[i] - '0') <= 7) {
1307       // Consume up to three octal characters.
1308       unsigned Value = Str[i] - '0';
1309
1310       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1311         ++i;
1312         Value = Value * 8 + (Str[i] - '0');
1313
1314         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1315           ++i;
1316           Value = Value * 8 + (Str[i] - '0');
1317         }
1318       }
1319
1320       if (Value > 255)
1321         return TokError("invalid octal escape sequence (out of range)");
1322
1323       Data += (unsigned char) Value;
1324       continue;
1325     }
1326
1327     // Otherwise recognize individual escapes.
1328     switch (Str[i]) {
1329     default:
1330       // Just reject invalid escape sequences for now.
1331       return TokError("invalid escape sequence (unrecognized character)");
1332
1333     case 'b': Data += '\b'; break;
1334     case 'f': Data += '\f'; break;
1335     case 'n': Data += '\n'; break;
1336     case 'r': Data += '\r'; break;
1337     case 't': Data += '\t'; break;
1338     case '"': Data += '"'; break;
1339     case '\\': Data += '\\'; break;
1340     }
1341   }
1342
1343   return false;
1344 }
1345
1346 /// ParseDirectiveAscii:
1347 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1348 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1349   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1350     CheckForValidSection();
1351
1352     for (;;) {
1353       if (getLexer().isNot(AsmToken::String))
1354         return TokError("expected string in '.ascii' or '.asciz' directive");
1355
1356       std::string Data;
1357       if (ParseEscapedString(Data))
1358         return true;
1359
1360       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1361       if (ZeroTerminated)
1362         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1363
1364       Lex();
1365
1366       if (getLexer().is(AsmToken::EndOfStatement))
1367         break;
1368
1369       if (getLexer().isNot(AsmToken::Comma))
1370         return TokError("unexpected token in '.ascii' or '.asciz' directive");
1371       Lex();
1372     }
1373   }
1374
1375   Lex();
1376   return false;
1377 }
1378
1379 /// ParseDirectiveValue
1380 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1381 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1382   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1383     CheckForValidSection();
1384
1385     for (;;) {
1386       const MCExpr *Value;
1387       SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
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 /// ParseDirectiveMacrosOnOff
2085 /// ::= .macros_on
2086 /// ::= .macros_off
2087 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2088                                                  SMLoc DirectiveLoc) {
2089   if (getLexer().isNot(AsmToken::EndOfStatement))
2090     return Error(getLexer().getLoc(),
2091                  "unexpected token in '" + Directive + "' directive");
2092
2093   getParser().MacrosEnabled = Directive == ".macros_on";
2094
2095   return false;
2096 }
2097
2098 /// ParseDirectiveMacro
2099 /// ::= .macro name
2100 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2101                                            SMLoc DirectiveLoc) {
2102   StringRef Name;
2103   if (getParser().ParseIdentifier(Name))
2104     return TokError("expected identifier in directive");
2105
2106   if (getLexer().isNot(AsmToken::EndOfStatement))
2107     return TokError("unexpected token in '.macro' directive");
2108
2109   // Eat the end of statement.
2110   Lex();
2111
2112   AsmToken EndToken, StartToken = getTok();
2113
2114   // Lex the macro definition.
2115   for (;;) {
2116     // Check whether we have reached the end of the file.
2117     if (getLexer().is(AsmToken::Eof))
2118       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2119
2120     // Otherwise, check whether we have reach the .endmacro.
2121     if (getLexer().is(AsmToken::Identifier) &&
2122         (getTok().getIdentifier() == ".endm" ||
2123          getTok().getIdentifier() == ".endmacro")) {
2124       EndToken = getTok();
2125       Lex();
2126       if (getLexer().isNot(AsmToken::EndOfStatement))
2127         return TokError("unexpected token in '" + EndToken.getIdentifier() +
2128                         "' directive");
2129       break;
2130     }
2131
2132     // Otherwise, scan til the end of the statement.
2133     getParser().EatToEndOfStatement();
2134   }
2135
2136   if (getParser().MacroMap.lookup(Name)) {
2137     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2138   }
2139
2140   const char *BodyStart = StartToken.getLoc().getPointer();
2141   const char *BodyEnd = EndToken.getLoc().getPointer();
2142   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2143   getParser().MacroMap[Name] = new Macro(Name, Body);
2144   return false;
2145 }
2146
2147 /// ParseDirectiveEndMacro
2148 /// ::= .endm
2149 /// ::= .endmacro
2150 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2151                                            SMLoc DirectiveLoc) {
2152   if (getLexer().isNot(AsmToken::EndOfStatement))
2153     return TokError("unexpected token in '" + Directive + "' directive");
2154
2155   // If we are inside a macro instantiation, terminate the current
2156   // instantiation.
2157   if (!getParser().ActiveMacros.empty()) {
2158     getParser().HandleMacroExit();
2159     return false;
2160   }
2161
2162   // Otherwise, this .endmacro is a stray entry in the file; well formed
2163   // .endmacro directives are handled during the macro definition parsing.
2164   return TokError("unexpected '" + Directive + "' in file, "
2165                   "no current macro definition");
2166 }
2167
2168 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2169   const uint64_t Mask = (1 << 7) - 1;
2170   do {
2171     unsigned Byte = Value & Mask;
2172     Value >>= 7;
2173     if (Value) // Not the last one
2174       Byte |= (1 << 7);
2175     getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2176   } while (Value);
2177 }
2178
2179 void GenericAsmParser::ParseSleb128(int64_t Value) {
2180   const int64_t Mask = (1 << 7) - 1;
2181   for(;;) {
2182     unsigned Byte = Value & Mask;
2183     Value >>= 7;
2184     bool Done = ((Value ==  0 && (Byte & 0x40) == 0) ||
2185                  (Value == -1 && (Byte & 0x40) != 0));
2186     if (!Done)
2187       Byte |= (1 << 7);
2188     getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2189     if (Done)
2190       break;
2191   }
2192 }
2193
2194 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2195   int64_t Value;
2196   if (getParser().ParseAbsoluteExpression(Value))
2197     return true;
2198
2199   if (getLexer().isNot(AsmToken::EndOfStatement))
2200     return TokError("unexpected token in directive");
2201
2202   if (DirName[1] == 's')
2203     ParseSleb128(Value);
2204   else
2205     ParseUleb128(Value);
2206   return false;
2207 }
2208
2209
2210 /// \brief Create an MCAsmParser instance.
2211 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2212                                      MCContext &C, MCStreamer &Out,
2213                                      const MCAsmInfo &MAI) {
2214   return new AsmParser(T, SM, C, Out, MAI);
2215 }