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