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