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