Better diagnostic for malformed .org assembly directive.
[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 void MarkUsed(const MCExpr *Value) {
1557   switch (Value->getKind()) {
1558   case MCExpr::Binary:
1559     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1560     MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1561     break;
1562   case MCExpr::Target:
1563   case MCExpr::Constant:
1564     break;
1565   case MCExpr::SymbolRef: {
1566     static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1567     break;
1568   }
1569   case MCExpr::Unary:
1570     MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1571     break;
1572   }
1573 }
1574
1575 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1576   // FIXME: Use better location, we should use proper tokens.
1577   SMLoc EqualLoc = Lexer.getLoc();
1578
1579   const MCExpr *Value;
1580   if (ParseExpression(Value))
1581     return true;
1582
1583   MarkUsed(Value);
1584
1585   if (Lexer.isNot(AsmToken::EndOfStatement))
1586     return TokError("unexpected token in assignment");
1587
1588   // Error on assignment to '.'.
1589   if (Name == ".") {
1590     return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1591                             "(use '.space' or '.org').)"));
1592   }
1593
1594   // Eat the end of statement marker.
1595   Lex();
1596
1597   // Validate that the LHS is allowed to be a variable (either it has not been
1598   // used as a symbol, or it is an absolute symbol).
1599   MCSymbol *Sym = getContext().LookupSymbol(Name);
1600   if (Sym) {
1601     // Diagnose assignment to a label.
1602     //
1603     // FIXME: Diagnostics. Note the location of the definition as a label.
1604     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1605     if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1606       ; // Allow redefinitions of undefined symbols only used in directives.
1607     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1608       return Error(EqualLoc, "redefinition of '" + Name + "'");
1609     else if (!Sym->isVariable())
1610       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1611     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1612       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1613                    Name + "'");
1614
1615     // Don't count these checks as uses.
1616     Sym->setUsed(false);
1617   } else
1618     Sym = getContext().GetOrCreateSymbol(Name);
1619
1620   // FIXME: Handle '.'.
1621
1622   // Do the assignment.
1623   Out.EmitAssignment(Sym, Value);
1624
1625   return false;
1626 }
1627
1628 /// ParseIdentifier:
1629 ///   ::= identifier
1630 ///   ::= string
1631 bool AsmParser::ParseIdentifier(StringRef &Res) {
1632   // The assembler has relaxed rules for accepting identifiers, in particular we
1633   // allow things like '.globl $foo', which would normally be separate
1634   // tokens. At this level, we have already lexed so we cannot (currently)
1635   // handle this as a context dependent token, instead we detect adjacent tokens
1636   // and return the combined identifier.
1637   if (Lexer.is(AsmToken::Dollar)) {
1638     SMLoc DollarLoc = getLexer().getLoc();
1639
1640     // Consume the dollar sign, and check for a following identifier.
1641     Lex();
1642     if (Lexer.isNot(AsmToken::Identifier))
1643       return true;
1644
1645     // We have a '$' followed by an identifier, make sure they are adjacent.
1646     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1647       return true;
1648
1649     // Construct the joined identifier and consume the token.
1650     Res = StringRef(DollarLoc.getPointer(),
1651                     getTok().getIdentifier().size() + 1);
1652     Lex();
1653     return false;
1654   }
1655
1656   if (Lexer.isNot(AsmToken::Identifier) &&
1657       Lexer.isNot(AsmToken::String))
1658     return true;
1659
1660   Res = getTok().getIdentifier();
1661
1662   Lex(); // Consume the identifier token.
1663
1664   return false;
1665 }
1666
1667 /// ParseDirectiveSet:
1668 ///   ::= .equ identifier ',' expression
1669 ///   ::= .equiv identifier ',' expression
1670 ///   ::= .set identifier ',' expression
1671 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1672   StringRef Name;
1673
1674   if (ParseIdentifier(Name))
1675     return TokError("expected identifier after '" + Twine(IDVal) + "'");
1676
1677   if (getLexer().isNot(AsmToken::Comma))
1678     return TokError("unexpected token in '" + Twine(IDVal) + "'");
1679   Lex();
1680
1681   return ParseAssignment(Name, allow_redef);
1682 }
1683
1684 bool AsmParser::ParseEscapedString(std::string &Data) {
1685   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1686
1687   Data = "";
1688   StringRef Str = getTok().getStringContents();
1689   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1690     if (Str[i] != '\\') {
1691       Data += Str[i];
1692       continue;
1693     }
1694
1695     // Recognize escaped characters. Note that this escape semantics currently
1696     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1697     ++i;
1698     if (i == e)
1699       return TokError("unexpected backslash at end of string");
1700
1701     // Recognize octal sequences.
1702     if ((unsigned) (Str[i] - '0') <= 7) {
1703       // Consume up to three octal characters.
1704       unsigned Value = Str[i] - '0';
1705
1706       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1707         ++i;
1708         Value = Value * 8 + (Str[i] - '0');
1709
1710         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1711           ++i;
1712           Value = Value * 8 + (Str[i] - '0');
1713         }
1714       }
1715
1716       if (Value > 255)
1717         return TokError("invalid octal escape sequence (out of range)");
1718
1719       Data += (unsigned char) Value;
1720       continue;
1721     }
1722
1723     // Otherwise recognize individual escapes.
1724     switch (Str[i]) {
1725     default:
1726       // Just reject invalid escape sequences for now.
1727       return TokError("invalid escape sequence (unrecognized character)");
1728
1729     case 'b': Data += '\b'; break;
1730     case 'f': Data += '\f'; break;
1731     case 'n': Data += '\n'; break;
1732     case 'r': Data += '\r'; break;
1733     case 't': Data += '\t'; break;
1734     case '"': Data += '"'; break;
1735     case '\\': Data += '\\'; break;
1736     }
1737   }
1738
1739   return false;
1740 }
1741
1742 /// ParseDirectiveAscii:
1743 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1744 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1745   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1746     CheckForValidSection();
1747
1748     for (;;) {
1749       if (getLexer().isNot(AsmToken::String))
1750         return TokError("expected string in '" + Twine(IDVal) + "' directive");
1751
1752       std::string Data;
1753       if (ParseEscapedString(Data))
1754         return true;
1755
1756       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1757       if (ZeroTerminated)
1758         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1759
1760       Lex();
1761
1762       if (getLexer().is(AsmToken::EndOfStatement))
1763         break;
1764
1765       if (getLexer().isNot(AsmToken::Comma))
1766         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1767       Lex();
1768     }
1769   }
1770
1771   Lex();
1772   return false;
1773 }
1774
1775 /// ParseDirectiveValue
1776 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1777 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1778   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1779     CheckForValidSection();
1780
1781     for (;;) {
1782       const MCExpr *Value;
1783       SMLoc ExprLoc = getLexer().getLoc();
1784       if (ParseExpression(Value))
1785         return true;
1786
1787       // Special case constant expressions to match code generator.
1788       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1789         assert(Size <= 8 && "Invalid size");
1790         uint64_t IntValue = MCE->getValue();
1791         if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1792           return Error(ExprLoc, "literal value out of range for directive");
1793         getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1794       } else
1795         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1796
1797       if (getLexer().is(AsmToken::EndOfStatement))
1798         break;
1799
1800       // FIXME: Improve diagnostic.
1801       if (getLexer().isNot(AsmToken::Comma))
1802         return TokError("unexpected token in directive");
1803       Lex();
1804     }
1805   }
1806
1807   Lex();
1808   return false;
1809 }
1810
1811 /// ParseDirectiveRealValue
1812 ///  ::= (.single | .double) [ expression (, expression)* ]
1813 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1814   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1815     CheckForValidSection();
1816
1817     for (;;) {
1818       // We don't truly support arithmetic on floating point expressions, so we
1819       // have to manually parse unary prefixes.
1820       bool IsNeg = false;
1821       if (getLexer().is(AsmToken::Minus)) {
1822         Lex();
1823         IsNeg = true;
1824       } else if (getLexer().is(AsmToken::Plus))
1825         Lex();
1826
1827       if (getLexer().isNot(AsmToken::Integer) &&
1828           getLexer().isNot(AsmToken::Real) &&
1829           getLexer().isNot(AsmToken::Identifier))
1830         return TokError("unexpected token in directive");
1831
1832       // Convert to an APFloat.
1833       APFloat Value(Semantics);
1834       StringRef IDVal = getTok().getString();
1835       if (getLexer().is(AsmToken::Identifier)) {
1836         if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1837           Value = APFloat::getInf(Semantics);
1838         else if (!IDVal.compare_lower("nan"))
1839           Value = APFloat::getNaN(Semantics, false, ~0);
1840         else
1841           return TokError("invalid floating point literal");
1842       } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1843           APFloat::opInvalidOp)
1844         return TokError("invalid floating point literal");
1845       if (IsNeg)
1846         Value.changeSign();
1847
1848       // Consume the numeric token.
1849       Lex();
1850
1851       // Emit the value as an integer.
1852       APInt AsInt = Value.bitcastToAPInt();
1853       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1854                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1855
1856       if (getLexer().is(AsmToken::EndOfStatement))
1857         break;
1858
1859       if (getLexer().isNot(AsmToken::Comma))
1860         return TokError("unexpected token in directive");
1861       Lex();
1862     }
1863   }
1864
1865   Lex();
1866   return false;
1867 }
1868
1869 /// ParseDirectiveSpace
1870 ///  ::= .space expression [ , expression ]
1871 bool AsmParser::ParseDirectiveSpace() {
1872   CheckForValidSection();
1873
1874   int64_t NumBytes;
1875   if (ParseAbsoluteExpression(NumBytes))
1876     return true;
1877
1878   int64_t FillExpr = 0;
1879   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1880     if (getLexer().isNot(AsmToken::Comma))
1881       return TokError("unexpected token in '.space' directive");
1882     Lex();
1883
1884     if (ParseAbsoluteExpression(FillExpr))
1885       return true;
1886
1887     if (getLexer().isNot(AsmToken::EndOfStatement))
1888       return TokError("unexpected token in '.space' directive");
1889   }
1890
1891   Lex();
1892
1893   if (NumBytes <= 0)
1894     return TokError("invalid number of bytes in '.space' directive");
1895
1896   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1897   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1898
1899   return false;
1900 }
1901
1902 /// ParseDirectiveZero
1903 ///  ::= .zero expression
1904 bool AsmParser::ParseDirectiveZero() {
1905   CheckForValidSection();
1906
1907   int64_t NumBytes;
1908   if (ParseAbsoluteExpression(NumBytes))
1909     return true;
1910
1911   int64_t Val = 0;
1912   if (getLexer().is(AsmToken::Comma)) {
1913     Lex();
1914     if (ParseAbsoluteExpression(Val))
1915       return true;
1916   }
1917
1918   if (getLexer().isNot(AsmToken::EndOfStatement))
1919     return TokError("unexpected token in '.zero' directive");
1920
1921   Lex();
1922
1923   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1924
1925   return false;
1926 }
1927
1928 /// ParseDirectiveFill
1929 ///  ::= .fill expression , expression , expression
1930 bool AsmParser::ParseDirectiveFill() {
1931   CheckForValidSection();
1932
1933   int64_t NumValues;
1934   if (ParseAbsoluteExpression(NumValues))
1935     return true;
1936
1937   if (getLexer().isNot(AsmToken::Comma))
1938     return TokError("unexpected token in '.fill' directive");
1939   Lex();
1940
1941   int64_t FillSize;
1942   if (ParseAbsoluteExpression(FillSize))
1943     return true;
1944
1945   if (getLexer().isNot(AsmToken::Comma))
1946     return TokError("unexpected token in '.fill' directive");
1947   Lex();
1948
1949   int64_t FillExpr;
1950   if (ParseAbsoluteExpression(FillExpr))
1951     return true;
1952
1953   if (getLexer().isNot(AsmToken::EndOfStatement))
1954     return TokError("unexpected token in '.fill' directive");
1955
1956   Lex();
1957
1958   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1959     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1960
1961   for (uint64_t i = 0, e = NumValues; i != e; ++i)
1962     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1963
1964   return false;
1965 }
1966
1967 /// ParseDirectiveOrg
1968 ///  ::= .org expression [ , expression ]
1969 bool AsmParser::ParseDirectiveOrg() {
1970   CheckForValidSection();
1971
1972   const MCExpr *Offset;
1973   SMLoc Loc = getTok().getLoc();
1974   if (ParseExpression(Offset))
1975     return true;
1976
1977   // Parse optional fill expression.
1978   int64_t FillExpr = 0;
1979   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1980     if (getLexer().isNot(AsmToken::Comma))
1981       return TokError("unexpected token in '.org' directive");
1982     Lex();
1983
1984     if (ParseAbsoluteExpression(FillExpr))
1985       return true;
1986
1987     if (getLexer().isNot(AsmToken::EndOfStatement))
1988       return TokError("unexpected token in '.org' directive");
1989   }
1990
1991   Lex();
1992
1993   // Only limited forms of relocatable expressions are accepted here, it
1994   // has to be relative to the current section. The streamer will return
1995   // 'true' if the expression wasn't evaluatable.
1996   if (getStreamer().EmitValueToOffset(Offset, FillExpr))
1997     return Error(Loc, "expected assembly-time absolute expression");
1998
1999   return false;
2000 }
2001
2002 /// ParseDirectiveAlign
2003 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
2004 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2005   CheckForValidSection();
2006
2007   SMLoc AlignmentLoc = getLexer().getLoc();
2008   int64_t Alignment;
2009   if (ParseAbsoluteExpression(Alignment))
2010     return true;
2011
2012   SMLoc MaxBytesLoc;
2013   bool HasFillExpr = false;
2014   int64_t FillExpr = 0;
2015   int64_t MaxBytesToFill = 0;
2016   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2017     if (getLexer().isNot(AsmToken::Comma))
2018       return TokError("unexpected token in directive");
2019     Lex();
2020
2021     // The fill expression can be omitted while specifying a maximum number of
2022     // alignment bytes, e.g:
2023     //  .align 3,,4
2024     if (getLexer().isNot(AsmToken::Comma)) {
2025       HasFillExpr = true;
2026       if (ParseAbsoluteExpression(FillExpr))
2027         return true;
2028     }
2029
2030     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2031       if (getLexer().isNot(AsmToken::Comma))
2032         return TokError("unexpected token in directive");
2033       Lex();
2034
2035       MaxBytesLoc = getLexer().getLoc();
2036       if (ParseAbsoluteExpression(MaxBytesToFill))
2037         return true;
2038
2039       if (getLexer().isNot(AsmToken::EndOfStatement))
2040         return TokError("unexpected token in directive");
2041     }
2042   }
2043
2044   Lex();
2045
2046   if (!HasFillExpr)
2047     FillExpr = 0;
2048
2049   // Compute alignment in bytes.
2050   if (IsPow2) {
2051     // FIXME: Diagnose overflow.
2052     if (Alignment >= 32) {
2053       Error(AlignmentLoc, "invalid alignment value");
2054       Alignment = 31;
2055     }
2056
2057     Alignment = 1ULL << Alignment;
2058   }
2059
2060   // Diagnose non-sensical max bytes to align.
2061   if (MaxBytesLoc.isValid()) {
2062     if (MaxBytesToFill < 1) {
2063       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2064             "many bytes, ignoring maximum bytes expression");
2065       MaxBytesToFill = 0;
2066     }
2067
2068     if (MaxBytesToFill >= Alignment) {
2069       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2070               "has no effect");
2071       MaxBytesToFill = 0;
2072     }
2073   }
2074
2075   // Check whether we should use optimal code alignment for this .align
2076   // directive.
2077   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2078   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2079       ValueSize == 1 && UseCodeAlign) {
2080     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2081   } else {
2082     // FIXME: Target specific behavior about how the "extra" bytes are filled.
2083     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2084                                        MaxBytesToFill);
2085   }
2086
2087   return false;
2088 }
2089
2090 /// ParseDirectiveSymbolAttribute
2091 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2092 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2093   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2094     for (;;) {
2095       StringRef Name;
2096       SMLoc Loc = getTok().getLoc();
2097
2098       if (ParseIdentifier(Name))
2099         return Error(Loc, "expected identifier in directive");
2100
2101       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2102
2103       // Assembler local symbols don't make any sense here. Complain loudly.
2104       if (Sym->isTemporary())
2105         return Error(Loc, "non-local symbol required in directive");
2106
2107       getStreamer().EmitSymbolAttribute(Sym, Attr);
2108
2109       if (getLexer().is(AsmToken::EndOfStatement))
2110         break;
2111
2112       if (getLexer().isNot(AsmToken::Comma))
2113         return TokError("unexpected token in directive");
2114       Lex();
2115     }
2116   }
2117
2118   Lex();
2119   return false;
2120 }
2121
2122 /// ParseDirectiveComm
2123 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2124 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2125   CheckForValidSection();
2126
2127   SMLoc IDLoc = getLexer().getLoc();
2128   StringRef Name;
2129   if (ParseIdentifier(Name))
2130     return TokError("expected identifier in directive");
2131
2132   // Handle the identifier as the key symbol.
2133   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2134
2135   if (getLexer().isNot(AsmToken::Comma))
2136     return TokError("unexpected token in directive");
2137   Lex();
2138
2139   int64_t Size;
2140   SMLoc SizeLoc = getLexer().getLoc();
2141   if (ParseAbsoluteExpression(Size))
2142     return true;
2143
2144   int64_t Pow2Alignment = 0;
2145   SMLoc Pow2AlignmentLoc;
2146   if (getLexer().is(AsmToken::Comma)) {
2147     Lex();
2148     Pow2AlignmentLoc = getLexer().getLoc();
2149     if (ParseAbsoluteExpression(Pow2Alignment))
2150       return true;
2151
2152     // If this target takes alignments in bytes (not log) validate and convert.
2153     if (Lexer.getMAI().getAlignmentIsInBytes()) {
2154       if (!isPowerOf2_64(Pow2Alignment))
2155         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2156       Pow2Alignment = Log2_64(Pow2Alignment);
2157     }
2158   }
2159
2160   if (getLexer().isNot(AsmToken::EndOfStatement))
2161     return TokError("unexpected token in '.comm' or '.lcomm' directive");
2162
2163   Lex();
2164
2165   // NOTE: a size of zero for a .comm should create a undefined symbol
2166   // but a size of .lcomm creates a bss symbol of size zero.
2167   if (Size < 0)
2168     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2169                  "be less than zero");
2170
2171   // NOTE: The alignment in the directive is a power of 2 value, the assembler
2172   // may internally end up wanting an alignment in bytes.
2173   // FIXME: Diagnose overflow.
2174   if (Pow2Alignment < 0)
2175     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2176                  "alignment, can't be less than zero");
2177
2178   if (!Sym->isUndefined())
2179     return Error(IDLoc, "invalid symbol redefinition");
2180
2181   // '.lcomm' is equivalent to '.zerofill'.
2182   // Create the Symbol as a common or local common with Size and Pow2Alignment
2183   if (IsLocal) {
2184     getStreamer().EmitZerofill(Ctx.getMachOSection(
2185                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2186                                  0, SectionKind::getBSS()),
2187                                Sym, Size, 1 << Pow2Alignment);
2188     return false;
2189   }
2190
2191   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2192   return false;
2193 }
2194
2195 /// ParseDirectiveAbort
2196 ///  ::= .abort [... message ...]
2197 bool AsmParser::ParseDirectiveAbort() {
2198   // FIXME: Use loc from directive.
2199   SMLoc Loc = getLexer().getLoc();
2200
2201   StringRef Str = ParseStringToEndOfStatement();
2202   if (getLexer().isNot(AsmToken::EndOfStatement))
2203     return TokError("unexpected token in '.abort' directive");
2204
2205   Lex();
2206
2207   if (Str.empty())
2208     Error(Loc, ".abort detected. Assembly stopping.");
2209   else
2210     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2211   // FIXME: Actually abort assembly here.
2212
2213   return false;
2214 }
2215
2216 /// ParseDirectiveInclude
2217 ///  ::= .include "filename"
2218 bool AsmParser::ParseDirectiveInclude() {
2219   if (getLexer().isNot(AsmToken::String))
2220     return TokError("expected string in '.include' directive");
2221
2222   std::string Filename = getTok().getString();
2223   SMLoc IncludeLoc = getLexer().getLoc();
2224   Lex();
2225
2226   if (getLexer().isNot(AsmToken::EndOfStatement))
2227     return TokError("unexpected token in '.include' directive");
2228
2229   // Strip the quotes.
2230   Filename = Filename.substr(1, Filename.size()-2);
2231
2232   // Attempt to switch the lexer to the included file before consuming the end
2233   // of statement to avoid losing it when we switch.
2234   if (EnterIncludeFile(Filename)) {
2235     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2236     return true;
2237   }
2238
2239   return false;
2240 }
2241
2242 /// ParseDirectiveIncbin
2243 ///  ::= .incbin "filename"
2244 bool AsmParser::ParseDirectiveIncbin() {
2245   if (getLexer().isNot(AsmToken::String))
2246     return TokError("expected string in '.incbin' directive");
2247
2248   std::string Filename = getTok().getString();
2249   SMLoc IncbinLoc = getLexer().getLoc();
2250   Lex();
2251
2252   if (getLexer().isNot(AsmToken::EndOfStatement))
2253     return TokError("unexpected token in '.incbin' directive");
2254
2255   // Strip the quotes.
2256   Filename = Filename.substr(1, Filename.size()-2);
2257
2258   // Attempt to process the included file.
2259   if (ProcessIncbinFile(Filename)) {
2260     Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2261     return true;
2262   }
2263
2264   return false;
2265 }
2266
2267 /// ParseDirectiveIf
2268 /// ::= .if expression
2269 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2270   TheCondStack.push_back(TheCondState);
2271   TheCondState.TheCond = AsmCond::IfCond;
2272   if(TheCondState.Ignore) {
2273     EatToEndOfStatement();
2274   }
2275   else {
2276     int64_t ExprValue;
2277     if (ParseAbsoluteExpression(ExprValue))
2278       return true;
2279
2280     if (getLexer().isNot(AsmToken::EndOfStatement))
2281       return TokError("unexpected token in '.if' directive");
2282
2283     Lex();
2284
2285     TheCondState.CondMet = ExprValue;
2286     TheCondState.Ignore = !TheCondState.CondMet;
2287   }
2288
2289   return false;
2290 }
2291
2292 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2293   StringRef Name;
2294   TheCondStack.push_back(TheCondState);
2295   TheCondState.TheCond = AsmCond::IfCond;
2296
2297   if (TheCondState.Ignore) {
2298     EatToEndOfStatement();
2299   } else {
2300     if (ParseIdentifier(Name))
2301       return TokError("expected identifier after '.ifdef'");
2302
2303     Lex();
2304
2305     MCSymbol *Sym = getContext().LookupSymbol(Name);
2306
2307     if (expect_defined)
2308       TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2309     else
2310       TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2311     TheCondState.Ignore = !TheCondState.CondMet;
2312   }
2313
2314   return false;
2315 }
2316
2317 /// ParseDirectiveElseIf
2318 /// ::= .elseif expression
2319 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2320   if (TheCondState.TheCond != AsmCond::IfCond &&
2321       TheCondState.TheCond != AsmCond::ElseIfCond)
2322       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2323                           " an .elseif");
2324   TheCondState.TheCond = AsmCond::ElseIfCond;
2325
2326   bool LastIgnoreState = false;
2327   if (!TheCondStack.empty())
2328       LastIgnoreState = TheCondStack.back().Ignore;
2329   if (LastIgnoreState || TheCondState.CondMet) {
2330     TheCondState.Ignore = true;
2331     EatToEndOfStatement();
2332   }
2333   else {
2334     int64_t ExprValue;
2335     if (ParseAbsoluteExpression(ExprValue))
2336       return true;
2337
2338     if (getLexer().isNot(AsmToken::EndOfStatement))
2339       return TokError("unexpected token in '.elseif' directive");
2340
2341     Lex();
2342     TheCondState.CondMet = ExprValue;
2343     TheCondState.Ignore = !TheCondState.CondMet;
2344   }
2345
2346   return false;
2347 }
2348
2349 /// ParseDirectiveElse
2350 /// ::= .else
2351 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2352   if (getLexer().isNot(AsmToken::EndOfStatement))
2353     return TokError("unexpected token in '.else' directive");
2354
2355   Lex();
2356
2357   if (TheCondState.TheCond != AsmCond::IfCond &&
2358       TheCondState.TheCond != AsmCond::ElseIfCond)
2359       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2360                           ".elseif");
2361   TheCondState.TheCond = AsmCond::ElseCond;
2362   bool LastIgnoreState = false;
2363   if (!TheCondStack.empty())
2364     LastIgnoreState = TheCondStack.back().Ignore;
2365   if (LastIgnoreState || TheCondState.CondMet)
2366     TheCondState.Ignore = true;
2367   else
2368     TheCondState.Ignore = false;
2369
2370   return false;
2371 }
2372
2373 /// ParseDirectiveEndIf
2374 /// ::= .endif
2375 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2376   if (getLexer().isNot(AsmToken::EndOfStatement))
2377     return TokError("unexpected token in '.endif' directive");
2378
2379   Lex();
2380
2381   if ((TheCondState.TheCond == AsmCond::NoCond) ||
2382       TheCondStack.empty())
2383     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2384                         ".else");
2385   if (!TheCondStack.empty()) {
2386     TheCondState = TheCondStack.back();
2387     TheCondStack.pop_back();
2388   }
2389
2390   return false;
2391 }
2392
2393 /// ParseDirectiveFile
2394 /// ::= .file [number] filename
2395 /// ::= .file number directory filename
2396 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2397   // FIXME: I'm not sure what this is.
2398   int64_t FileNumber = -1;
2399   SMLoc FileNumberLoc = getLexer().getLoc();
2400   if (getLexer().is(AsmToken::Integer)) {
2401     FileNumber = getTok().getIntVal();
2402     Lex();
2403
2404     if (FileNumber < 1)
2405       return TokError("file number less than one");
2406   }
2407
2408   if (getLexer().isNot(AsmToken::String))
2409     return TokError("unexpected token in '.file' directive");
2410
2411   // Usually the directory and filename together, otherwise just the directory.
2412   StringRef Path = getTok().getString();
2413   Path = Path.substr(1, Path.size()-2);
2414   Lex();
2415
2416   StringRef Directory;
2417   StringRef Filename;
2418   if (getLexer().is(AsmToken::String)) {
2419     if (FileNumber == -1)
2420       return TokError("explicit path specified, but no file number");
2421     Filename = getTok().getString();
2422     Filename = Filename.substr(1, Filename.size()-2);
2423     Directory = Path;
2424     Lex();
2425   } else {
2426     Filename = Path;
2427   }
2428
2429   if (getLexer().isNot(AsmToken::EndOfStatement))
2430     return TokError("unexpected token in '.file' directive");
2431
2432   if (FileNumber == -1)
2433     getStreamer().EmitFileDirective(Filename);
2434   else {
2435     if (getContext().getGenDwarfForAssembly() == true)
2436       Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2437                         "used to generate dwarf debug info for assembly code");
2438
2439     if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2440       Error(FileNumberLoc, "file number already allocated");
2441   }
2442
2443   return false;
2444 }
2445
2446 /// ParseDirectiveLine
2447 /// ::= .line [number]
2448 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2449   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2450     if (getLexer().isNot(AsmToken::Integer))
2451       return TokError("unexpected token in '.line' directive");
2452
2453     int64_t LineNumber = getTok().getIntVal();
2454     (void) LineNumber;
2455     Lex();
2456
2457     // FIXME: Do something with the .line.
2458   }
2459
2460   if (getLexer().isNot(AsmToken::EndOfStatement))
2461     return TokError("unexpected token in '.line' directive");
2462
2463   return false;
2464 }
2465
2466
2467 /// ParseDirectiveLoc
2468 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2469 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2470 /// The first number is a file number, must have been previously assigned with
2471 /// a .file directive, the second number is the line number and optionally the
2472 /// third number is a column position (zero if not specified).  The remaining
2473 /// optional items are .loc sub-directives.
2474 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2475
2476   if (getLexer().isNot(AsmToken::Integer))
2477     return TokError("unexpected token in '.loc' directive");
2478   int64_t FileNumber = getTok().getIntVal();
2479   if (FileNumber < 1)
2480     return TokError("file number less than one in '.loc' directive");
2481   if (!getContext().isValidDwarfFileNumber(FileNumber))
2482     return TokError("unassigned file number in '.loc' directive");
2483   Lex();
2484
2485   int64_t LineNumber = 0;
2486   if (getLexer().is(AsmToken::Integer)) {
2487     LineNumber = getTok().getIntVal();
2488     if (LineNumber < 1)
2489       return TokError("line number less than one in '.loc' directive");
2490     Lex();
2491   }
2492
2493   int64_t ColumnPos = 0;
2494   if (getLexer().is(AsmToken::Integer)) {
2495     ColumnPos = getTok().getIntVal();
2496     if (ColumnPos < 0)
2497       return TokError("column position less than zero in '.loc' directive");
2498     Lex();
2499   }
2500
2501   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2502   unsigned Isa = 0;
2503   int64_t Discriminator = 0;
2504   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2505     for (;;) {
2506       if (getLexer().is(AsmToken::EndOfStatement))
2507         break;
2508
2509       StringRef Name;
2510       SMLoc Loc = getTok().getLoc();
2511       if (getParser().ParseIdentifier(Name))
2512         return TokError("unexpected token in '.loc' directive");
2513
2514       if (Name == "basic_block")
2515         Flags |= DWARF2_FLAG_BASIC_BLOCK;
2516       else if (Name == "prologue_end")
2517         Flags |= DWARF2_FLAG_PROLOGUE_END;
2518       else if (Name == "epilogue_begin")
2519         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2520       else if (Name == "is_stmt") {
2521         SMLoc Loc = getTok().getLoc();
2522         const MCExpr *Value;
2523         if (getParser().ParseExpression(Value))
2524           return true;
2525         // The expression must be the constant 0 or 1.
2526         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2527           int Value = MCE->getValue();
2528           if (Value == 0)
2529             Flags &= ~DWARF2_FLAG_IS_STMT;
2530           else if (Value == 1)
2531             Flags |= DWARF2_FLAG_IS_STMT;
2532           else
2533             return Error(Loc, "is_stmt value not 0 or 1");
2534         }
2535         else {
2536           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2537         }
2538       }
2539       else if (Name == "isa") {
2540         SMLoc Loc = getTok().getLoc();
2541         const MCExpr *Value;
2542         if (getParser().ParseExpression(Value))
2543           return true;
2544         // The expression must be a constant greater or equal to 0.
2545         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2546           int Value = MCE->getValue();
2547           if (Value < 0)
2548             return Error(Loc, "isa number less than zero");
2549           Isa = Value;
2550         }
2551         else {
2552           return Error(Loc, "isa number not a constant value");
2553         }
2554       }
2555       else if (Name == "discriminator") {
2556         if (getParser().ParseAbsoluteExpression(Discriminator))
2557           return true;
2558       }
2559       else {
2560         return Error(Loc, "unknown sub-directive in '.loc' directive");
2561       }
2562
2563       if (getLexer().is(AsmToken::EndOfStatement))
2564         break;
2565     }
2566   }
2567
2568   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2569                                       Isa, Discriminator, StringRef());
2570
2571   return false;
2572 }
2573
2574 /// ParseDirectiveStabs
2575 /// ::= .stabs string, number, number, number
2576 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2577                                            SMLoc DirectiveLoc) {
2578   return TokError("unsupported directive '" + Directive + "'");
2579 }
2580
2581 /// ParseDirectiveCFISections
2582 /// ::= .cfi_sections section [, section]
2583 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2584                                                  SMLoc DirectiveLoc) {
2585   StringRef Name;
2586   bool EH = false;
2587   bool Debug = false;
2588
2589   if (getParser().ParseIdentifier(Name))
2590     return TokError("Expected an identifier");
2591
2592   if (Name == ".eh_frame")
2593     EH = true;
2594   else if (Name == ".debug_frame")
2595     Debug = true;
2596
2597   if (getLexer().is(AsmToken::Comma)) {
2598     Lex();
2599
2600     if (getParser().ParseIdentifier(Name))
2601       return TokError("Expected an identifier");
2602
2603     if (Name == ".eh_frame")
2604       EH = true;
2605     else if (Name == ".debug_frame")
2606       Debug = true;
2607   }
2608
2609   getStreamer().EmitCFISections(EH, Debug);
2610
2611   return false;
2612 }
2613
2614 /// ParseDirectiveCFIStartProc
2615 /// ::= .cfi_startproc
2616 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2617                                                   SMLoc DirectiveLoc) {
2618   getStreamer().EmitCFIStartProc();
2619   return false;
2620 }
2621
2622 /// ParseDirectiveCFIEndProc
2623 /// ::= .cfi_endproc
2624 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2625   getStreamer().EmitCFIEndProc();
2626   return false;
2627 }
2628
2629 /// ParseRegisterOrRegisterNumber - parse register name or number.
2630 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2631                                                      SMLoc DirectiveLoc) {
2632   unsigned RegNo;
2633
2634   if (getLexer().isNot(AsmToken::Integer)) {
2635     if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2636       DirectiveLoc))
2637       return true;
2638     Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2639   } else
2640     return getParser().ParseAbsoluteExpression(Register);
2641
2642   return false;
2643 }
2644
2645 /// ParseDirectiveCFIDefCfa
2646 /// ::= .cfi_def_cfa register,  offset
2647 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2648                                                SMLoc DirectiveLoc) {
2649   int64_t Register = 0;
2650   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2651     return true;
2652
2653   if (getLexer().isNot(AsmToken::Comma))
2654     return TokError("unexpected token in directive");
2655   Lex();
2656
2657   int64_t Offset = 0;
2658   if (getParser().ParseAbsoluteExpression(Offset))
2659     return true;
2660
2661   getStreamer().EmitCFIDefCfa(Register, Offset);
2662   return false;
2663 }
2664
2665 /// ParseDirectiveCFIDefCfaOffset
2666 /// ::= .cfi_def_cfa_offset offset
2667 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2668                                                      SMLoc DirectiveLoc) {
2669   int64_t Offset = 0;
2670   if (getParser().ParseAbsoluteExpression(Offset))
2671     return true;
2672
2673   getStreamer().EmitCFIDefCfaOffset(Offset);
2674   return false;
2675 }
2676
2677 /// ParseDirectiveCFIAdjustCfaOffset
2678 /// ::= .cfi_adjust_cfa_offset adjustment
2679 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2680                                                         SMLoc DirectiveLoc) {
2681   int64_t Adjustment = 0;
2682   if (getParser().ParseAbsoluteExpression(Adjustment))
2683     return true;
2684
2685   getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2686   return false;
2687 }
2688
2689 /// ParseDirectiveCFIDefCfaRegister
2690 /// ::= .cfi_def_cfa_register register
2691 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2692                                                        SMLoc DirectiveLoc) {
2693   int64_t Register = 0;
2694   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2695     return true;
2696
2697   getStreamer().EmitCFIDefCfaRegister(Register);
2698   return false;
2699 }
2700
2701 /// ParseDirectiveCFIOffset
2702 /// ::= .cfi_offset register, offset
2703 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2704   int64_t Register = 0;
2705   int64_t Offset = 0;
2706
2707   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2708     return true;
2709
2710   if (getLexer().isNot(AsmToken::Comma))
2711     return TokError("unexpected token in directive");
2712   Lex();
2713
2714   if (getParser().ParseAbsoluteExpression(Offset))
2715     return true;
2716
2717   getStreamer().EmitCFIOffset(Register, Offset);
2718   return false;
2719 }
2720
2721 /// ParseDirectiveCFIRelOffset
2722 /// ::= .cfi_rel_offset register, offset
2723 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2724                                                   SMLoc DirectiveLoc) {
2725   int64_t Register = 0;
2726
2727   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2728     return true;
2729
2730   if (getLexer().isNot(AsmToken::Comma))
2731     return TokError("unexpected token in directive");
2732   Lex();
2733
2734   int64_t Offset = 0;
2735   if (getParser().ParseAbsoluteExpression(Offset))
2736     return true;
2737
2738   getStreamer().EmitCFIRelOffset(Register, Offset);
2739   return false;
2740 }
2741
2742 static bool isValidEncoding(int64_t Encoding) {
2743   if (Encoding & ~0xff)
2744     return false;
2745
2746   if (Encoding == dwarf::DW_EH_PE_omit)
2747     return true;
2748
2749   const unsigned Format = Encoding & 0xf;
2750   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2751       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2752       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2753       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2754     return false;
2755
2756   const unsigned Application = Encoding & 0x70;
2757   if (Application != dwarf::DW_EH_PE_absptr &&
2758       Application != dwarf::DW_EH_PE_pcrel)
2759     return false;
2760
2761   return true;
2762 }
2763
2764 /// ParseDirectiveCFIPersonalityOrLsda
2765 /// ::= .cfi_personality encoding, [symbol_name]
2766 /// ::= .cfi_lsda encoding, [symbol_name]
2767 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2768                                                     SMLoc DirectiveLoc) {
2769   int64_t Encoding = 0;
2770   if (getParser().ParseAbsoluteExpression(Encoding))
2771     return true;
2772   if (Encoding == dwarf::DW_EH_PE_omit)
2773     return false;
2774
2775   if (!isValidEncoding(Encoding))
2776     return TokError("unsupported encoding.");
2777
2778   if (getLexer().isNot(AsmToken::Comma))
2779     return TokError("unexpected token in directive");
2780   Lex();
2781
2782   StringRef Name;
2783   if (getParser().ParseIdentifier(Name))
2784     return TokError("expected identifier in directive");
2785
2786   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2787
2788   if (IDVal == ".cfi_personality")
2789     getStreamer().EmitCFIPersonality(Sym, Encoding);
2790   else {
2791     assert(IDVal == ".cfi_lsda");
2792     getStreamer().EmitCFILsda(Sym, Encoding);
2793   }
2794   return false;
2795 }
2796
2797 /// ParseDirectiveCFIRememberState
2798 /// ::= .cfi_remember_state
2799 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2800                                                       SMLoc DirectiveLoc) {
2801   getStreamer().EmitCFIRememberState();
2802   return false;
2803 }
2804
2805 /// ParseDirectiveCFIRestoreState
2806 /// ::= .cfi_remember_state
2807 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2808                                                      SMLoc DirectiveLoc) {
2809   getStreamer().EmitCFIRestoreState();
2810   return false;
2811 }
2812
2813 /// ParseDirectiveCFISameValue
2814 /// ::= .cfi_same_value register
2815 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2816                                                   SMLoc DirectiveLoc) {
2817   int64_t Register = 0;
2818
2819   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2820     return true;
2821
2822   getStreamer().EmitCFISameValue(Register);
2823
2824   return false;
2825 }
2826
2827 /// ParseDirectiveCFIRestore
2828 /// ::= .cfi_restore register
2829 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2830                                                 SMLoc DirectiveLoc) {
2831   int64_t Register = 0;
2832   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2833     return true;
2834
2835   getStreamer().EmitCFIRestore(Register);
2836
2837   return false;
2838 }
2839
2840 /// ParseDirectiveCFIEscape
2841 /// ::= .cfi_escape expression[,...]
2842 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2843                                                SMLoc DirectiveLoc) {
2844   std::string Values;
2845   int64_t CurrValue;
2846   if (getParser().ParseAbsoluteExpression(CurrValue))
2847     return true;
2848
2849   Values.push_back((uint8_t)CurrValue);
2850
2851   while (getLexer().is(AsmToken::Comma)) {
2852     Lex();
2853
2854     if (getParser().ParseAbsoluteExpression(CurrValue))
2855       return true;
2856
2857     Values.push_back((uint8_t)CurrValue);
2858   }
2859
2860   getStreamer().EmitCFIEscape(Values);
2861   return false;
2862 }
2863
2864 /// ParseDirectiveCFISignalFrame
2865 /// ::= .cfi_signal_frame
2866 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2867                                                     SMLoc DirectiveLoc) {
2868   if (getLexer().isNot(AsmToken::EndOfStatement))
2869     return Error(getLexer().getLoc(),
2870                  "unexpected token in '" + Directive + "' directive");
2871
2872   getStreamer().EmitCFISignalFrame();
2873
2874   return false;
2875 }
2876
2877 /// ParseDirectiveMacrosOnOff
2878 /// ::= .macros_on
2879 /// ::= .macros_off
2880 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2881                                                  SMLoc DirectiveLoc) {
2882   if (getLexer().isNot(AsmToken::EndOfStatement))
2883     return Error(getLexer().getLoc(),
2884                  "unexpected token in '" + Directive + "' directive");
2885
2886   getParser().MacrosEnabled = Directive == ".macros_on";
2887
2888   return false;
2889 }
2890
2891 /// ParseDirectiveMacro
2892 /// ::= .macro name [parameters]
2893 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2894                                            SMLoc DirectiveLoc) {
2895   StringRef Name;
2896   if (getParser().ParseIdentifier(Name))
2897     return TokError("expected identifier in directive");
2898
2899   std::vector<StringRef> Parameters;
2900   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2901     for(;;) {
2902       StringRef Parameter;
2903       if (getParser().ParseIdentifier(Parameter))
2904         return TokError("expected identifier in directive");
2905       Parameters.push_back(Parameter);
2906
2907       if (getLexer().isNot(AsmToken::Comma))
2908         break;
2909       Lex();
2910     }
2911   }
2912
2913   if (getLexer().isNot(AsmToken::EndOfStatement))
2914     return TokError("unexpected token in '.macro' directive");
2915
2916   // Eat the end of statement.
2917   Lex();
2918
2919   AsmToken EndToken, StartToken = getTok();
2920
2921   // Lex the macro definition.
2922   for (;;) {
2923     // Check whether we have reached the end of the file.
2924     if (getLexer().is(AsmToken::Eof))
2925       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2926
2927     // Otherwise, check whether we have reach the .endmacro.
2928     if (getLexer().is(AsmToken::Identifier) &&
2929         (getTok().getIdentifier() == ".endm" ||
2930          getTok().getIdentifier() == ".endmacro")) {
2931       EndToken = getTok();
2932       Lex();
2933       if (getLexer().isNot(AsmToken::EndOfStatement))
2934         return TokError("unexpected token in '" + EndToken.getIdentifier() +
2935                         "' directive");
2936       break;
2937     }
2938
2939     // Otherwise, scan til the end of the statement.
2940     getParser().EatToEndOfStatement();
2941   }
2942
2943   if (getParser().MacroMap.lookup(Name)) {
2944     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2945   }
2946
2947   const char *BodyStart = StartToken.getLoc().getPointer();
2948   const char *BodyEnd = EndToken.getLoc().getPointer();
2949   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2950   getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2951   return false;
2952 }
2953
2954 /// ParseDirectiveEndMacro
2955 /// ::= .endm
2956 /// ::= .endmacro
2957 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2958                                            SMLoc DirectiveLoc) {
2959   if (getLexer().isNot(AsmToken::EndOfStatement))
2960     return TokError("unexpected token in '" + Directive + "' directive");
2961
2962   // If we are inside a macro instantiation, terminate the current
2963   // instantiation.
2964   if (!getParser().ActiveMacros.empty()) {
2965     getParser().HandleMacroExit();
2966     return false;
2967   }
2968
2969   // Otherwise, this .endmacro is a stray entry in the file; well formed
2970   // .endmacro directives are handled during the macro definition parsing.
2971   return TokError("unexpected '" + Directive + "' in file, "
2972                   "no current macro definition");
2973 }
2974
2975 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2976   getParser().CheckForValidSection();
2977
2978   const MCExpr *Value;
2979
2980   if (getParser().ParseExpression(Value))
2981     return true;
2982
2983   if (getLexer().isNot(AsmToken::EndOfStatement))
2984     return TokError("unexpected token in directive");
2985
2986   if (DirName[1] == 's')
2987     getStreamer().EmitSLEB128Value(Value);
2988   else
2989     getStreamer().EmitULEB128Value(Value);
2990
2991   return false;
2992 }
2993
2994
2995 /// \brief Create an MCAsmParser instance.
2996 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2997                                      MCContext &C, MCStreamer &Out,
2998                                      const MCAsmInfo &MAI) {
2999   return new AsmParser(SM, C, Out, MAI);
3000 }