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