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