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