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