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