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