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