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