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