blob: 21cbd3416ca5183cafac42cc9d782b811f96df4a [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- 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
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Chad Rosierabde6752013-02-13 18:38:58 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000025#include "llvm/MC/MCParser/AsmCond.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000029#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000030#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000031#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000033#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000034#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000035#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000036#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000039#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000040#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000041#include <set>
42#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000043#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000044using namespace llvm;
45
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000046static cl::opt<bool>
47FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
49
Eric Christopher2318ba12012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000051
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000052namespace {
53
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000054/// \brief Helper types for tracking macro definitions.
55typedef std::vector<AsmToken> MCAsmMacroArgument;
56typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
59
60struct MCAsmMacro {
61 StringRef Name;
62 StringRef Body;
63 MCAsmMacroParameters Parameters;
64
65public:
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
68
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
71};
72
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000073/// \brief Helper class for storing information about an active macro
74/// instantiation.
75struct MacroInstantiation {
76 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000077 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
81
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
84
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000085 /// The buffer where parsing should resume upon instantiation completion.
86 int ExitBuffer;
87
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000088 /// The location where parsing should resume upon instantiation completion.
89 SMLoc ExitLoc;
90
91public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000092 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000093 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000094};
95
Eli Friedman2128aae2012-10-22 23:58:19 +000096struct ParseStatementInfo {
Jim Grosbach4a200922013-09-20 23:08:21 +000097 /// \brief The parsed operands from the last parsed statement.
Eli Friedman2128aae2012-10-22 23:58:19 +000098 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
Jim Grosbach4a200922013-09-20 23:08:21 +0000100 /// \brief The opcode from the last parsed instruction.
Eli Friedman2128aae2012-10-22 23:58:19 +0000101 unsigned Opcode;
102
Jim Grosbach4a200922013-09-20 23:08:21 +0000103 /// \brief Was there an error parsing the inline assembly?
Chad Rosier57498012012-12-12 22:45:52 +0000104 bool ParseError;
105
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Chad Rosier57498012012-12-12 22:45:52 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000111
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
117 }
118};
119
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120/// \brief The concrete assembly parser instance.
121class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// 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
Jim Grosbach4a200922013-09-20 23:08:21 +0000141 /// \brief maps directive names to handler methods in parser
Eli Bendersky6ee13082013-01-15 22:59:42 +0000142 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000143 /// addDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000145
Jim Grosbach4a200922013-09-20 23:08:21 +0000146 /// \brief Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Jim Grosbach4a200922013-09-20 23:08:21 +0000149 /// \brief Stack of active macro instantiations.
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000150 std::vector<MacroInstantiation*> ActiveMacros;
151
Jim Grosbach4a200922013-09-20 23:08:21 +0000152 /// \brief List of bodies of anonymous macros.
Benjamin Kramera2b0c332013-08-04 09:06:29 +0000153 std::deque<MCAsmMacro> MacroLikeBodies;
154
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000155 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000156 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000157
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
160
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
164 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000165 int CppHashBuf;
Kevin Enderbya8959492013-06-21 20:51:39 +0000166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000168 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderbya8959492013-06-21 20:51:39 +0000169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
171 int LastQueryBuffer;
172 unsigned LastQueryLine;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000173
Devang Patel0db58bf2012-01-31 18:14:05 +0000174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
176
Jim Grosbach4a200922013-09-20 23:08:21 +0000177 /// \brief is Darwin compatibility enabled?
Preston Gurd7b6f2032012-09-19 20:36:12 +0000178 bool IsDarwin;
179
Jim Grosbach4a200922013-09-20 23:08:21 +0000180 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000181 bool ParsingInlineAsm;
182
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000185 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000186 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000187
188 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
189
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000190 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000191 ExtensionDirectiveHandler Handler) {
192 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000193 }
194
195public:
196 /// @name MCAsmParser Interface
197 /// {
198
199 virtual SourceMgr &getSourceManager() { return SrcMgr; }
200 virtual MCAsmLexer &getLexer() { return Lexer; }
201 virtual MCContext &getContext() { return Ctx; }
202 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000203 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000204 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000205 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000206 else
207 return AssemblerDialect;
208 }
209 virtual void setAssemblerDialect(unsigned i) {
210 AssemblerDialect = i;
211 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000212
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000213 virtual bool Warning(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000214 ArrayRef<SMRange> Ranges = None);
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000215 virtual bool Error(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000216 ArrayRef<SMRange> Ranges = None);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000217
Craig Topper345d16d2012-08-29 05:48:09 +0000218 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000219
Chad Rosier84125ca2012-10-13 00:26:04 +0000220 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000221 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000222
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000223 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000224 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000225 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000226 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000227 SmallVectorImpl<std::string> &Clobbers,
228 const MCInstrInfo *MII,
229 const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000231
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000232 bool parseExpression(const MCExpr *&Res);
233 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
Chad Rosierba69b362013-04-10 17:35:30 +0000234 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000235 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000237
Jim Grosbach4a200922013-09-20 23:08:21 +0000238 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000239 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000240 virtual bool parseIdentifier(StringRef &Res);
241 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000242
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000243 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000244 /// }
245
246private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000247
Jim Grosbach4a200922013-09-20 23:08:21 +0000248 bool parseStatement(ParseStatementInfo &Info);
249 void eatToEndOfLine();
250 bool parseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000251
Jim Grosbach4a200922013-09-20 23:08:21 +0000252 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Kevin Enderby221514e2013-01-22 21:44:53 +0000253 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000254 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000255 const MCAsmMacroParameters &Parameters,
256 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000257 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000258
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000259 /// \brief Are macros enabled in the parser?
Jim Grosbach4a200922013-09-20 23:08:21 +0000260 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000261
262 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4a200922013-09-20 23:08:21 +0000263 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000264
265 /// \brief Lookup a previously defined macro.
266 /// \param Name Macro name.
267 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4a200922013-09-20 23:08:21 +0000268 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000269
270 /// \brief Define a new macro with the given name and information.
Jim Grosbach4a200922013-09-20 23:08:21 +0000271 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000272
273 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4a200922013-09-20 23:08:21 +0000274 void undefineMacro(StringRef Name);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000275
276 /// \brief Are we inside a macro instantiation?
Jim Grosbach4a200922013-09-20 23:08:21 +0000277 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000278
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000279 /// \brief Handle entry to macro instantiation.
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000280 ///
281 /// \param M The macro.
282 /// \param NameLoc Instantiation location.
Jim Grosbach4a200922013-09-20 23:08:21 +0000283 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000284
285 /// \brief Handle exit from macro instantiation.
Jim Grosbach4a200922013-09-20 23:08:21 +0000286 void handleMacroExit();
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000287
288 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
289 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
290 /// correct delimiter by the method.
Jim Grosbach4a200922013-09-20 23:08:21 +0000291 bool parseMacroArgument(MCAsmMacroArgument &MA,
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000292 AsmToken::TokenKind &ArgumentDelimiter);
293
294 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4a200922013-09-20 23:08:21 +0000295 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000296
Jim Grosbach4a200922013-09-20 23:08:21 +0000297 void printMacroInstantiations();
298 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000299 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner462b43c2011-10-16 05:47:55 +0000300 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000301 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000302 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000303
Jim Grosbach4a200922013-09-20 23:08:21 +0000304 /// \brief Enter the specified file. This returns true on failure.
305 bool enterIncludeFile(const std::string &Filename);
306
307 /// \brief Process the specified file for the .incbin directive.
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000308 /// This returns true on failure.
Jim Grosbach4a200922013-09-20 23:08:21 +0000309 bool processIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000310
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000311 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000312 /// current token is not set; clients should ensure Lex() is called
313 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000314 ///
315 /// \param InBuffer If not -1, should be the known buffer id that contains the
316 /// location.
Jim Grosbach4a200922013-09-20 23:08:21 +0000317 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000318
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000319 /// \brief Parse up to the end of statement and a return the contents from the
320 /// current token until the end of the statement; the current token on exit
321 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000322 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000323
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000324 /// \brief Parse until the end of a statement or a comma is encountered,
325 /// return the contents from the current token up to the end or comma.
Jim Grosbach4a200922013-09-20 23:08:21 +0000326 StringRef parseStringToComma();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000327
Jim Grosbach4a200922013-09-20 23:08:21 +0000328 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000329 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000330
Jim Grosbach4a200922013-09-20 23:08:21 +0000331 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000334
Jim Grosbach4a200922013-09-20 23:08:21 +0000335 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000336
Eli Bendersky6ee13082013-01-15 22:59:42 +0000337 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000338 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000339 DK_NO_DIRECTIVE, // Placeholder
340 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
341 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
342 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000343 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000344 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby4f066b62013-08-28 17:50:59 +0000345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
358 DK_CFI_REGISTER,
359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000361 };
362
Jim Grosbach4a200922013-09-20 23:08:21 +0000363 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky6ee13082013-01-15 22:59:42 +0000364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000366
367 // ".ascii", ".asciz", ".string"
Jim Grosbach4a200922013-09-20 23:08:21 +0000368 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
371 bool parseDirectiveFill(); // ".fill"
372 bool parseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000373 // ".set", ".equ", ".equiv"
Jim Grosbach4a200922013-09-20 23:08:21 +0000374 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
375 bool parseDirectiveOrg(); // ".org"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000376 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4a200922013-09-20 23:08:21 +0000377 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000378
Eli Bendersky6ee13082013-01-15 22:59:42 +0000379 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4a200922013-09-20 23:08:21 +0000380 bool parseDirectiveFile(SMLoc DirectiveLoc);
381 bool parseDirectiveLine();
382 bool parseDirectiveLoc();
383 bool parseDirectiveStabs();
Eli Bendersky6ee13082013-01-15 22:59:42 +0000384
385 // .cfi directives
Jim Grosbach4a200922013-09-20 23:08:21 +0000386 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
387 bool parseDirectiveCFISections();
388 bool parseDirectiveCFIStartProc();
389 bool parseDirectiveCFIEndProc();
390 bool parseDirectiveCFIDefCfaOffset();
391 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
392 bool parseDirectiveCFIAdjustCfaOffset();
393 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
397 bool parseDirectiveCFIRememberState();
398 bool parseDirectiveCFIRestoreState();
399 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIEscape();
402 bool parseDirectiveCFISignalFrame();
403 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000404
405 // macro directives
Jim Grosbach4a200922013-09-20 23:08:21 +0000406 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
407 bool parseDirectiveEndMacro(StringRef Directive);
408 bool parseDirectiveMacro(SMLoc DirectiveLoc);
409 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000410
Eli Bendersky4766ef42012-12-20 19:05:53 +0000411 // ".bundle_align_mode"
Jim Grosbach4a200922013-09-20 23:08:21 +0000412 bool parseDirectiveBundleAlignMode();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000413 // ".bundle_lock"
Jim Grosbach4a200922013-09-20 23:08:21 +0000414 bool parseDirectiveBundleLock();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000415 // ".bundle_unlock"
Jim Grosbach4a200922013-09-20 23:08:21 +0000416 bool parseDirectiveBundleUnlock();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000417
Eli Bendersky6ee13082013-01-15 22:59:42 +0000418 // ".space", ".skip"
Jim Grosbach4a200922013-09-20 23:08:21 +0000419 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000420
421 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4a200922013-09-20 23:08:21 +0000422 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky6ee13082013-01-15 22:59:42 +0000423
Jim Grosbach4a200922013-09-20 23:08:21 +0000424 /// \brief Parse a directive like ".globl" which
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000425 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4a200922013-09-20 23:08:21 +0000426 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000427
Jim Grosbach4a200922013-09-20 23:08:21 +0000428 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000429
Jim Grosbach4a200922013-09-20 23:08:21 +0000430 bool parseDirectiveAbort(); // ".abort"
431 bool parseDirectiveInclude(); // ".include"
432 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000433
Jim Grosbach4a200922013-09-20 23:08:21 +0000434 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000435 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4a200922013-09-20 23:08:21 +0000436 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000437 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4a200922013-09-20 23:08:21 +0000438 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000439 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4a200922013-09-20 23:08:21 +0000440 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
441 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
442 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
443 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000444 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000445
Jim Grosbach4a200922013-09-20 23:08:21 +0000446 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbarcceba832010-09-17 02:47:07 +0000447 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000448
Rafael Espindola761cb062012-06-03 23:57:14 +0000449 // Macro-like directives
Jim Grosbach4a200922013-09-20 23:08:21 +0000450 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
451 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000452 raw_svector_ostream &OS);
Jim Grosbach4a200922013-09-20 23:08:21 +0000453 bool parseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
454 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
455 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
456 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000457
Chad Rosier469b1442013-02-12 21:33:51 +0000458 // "_emit" or "__emit"
Jim Grosbach4a200922013-09-20 23:08:21 +0000459 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosier469b1442013-02-12 21:33:51 +0000460 size_t Len);
461
462 // "align"
Jim Grosbach4a200922013-09-20 23:08:21 +0000463 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000464
Eli Bendersky6ee13082013-01-15 22:59:42 +0000465 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000466};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000467}
468
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000469namespace llvm {
470
471extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000472extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000473extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000474
475}
476
Chris Lattneraaec2052010-01-19 19:46:13 +0000477enum { DEFAULT_ADDRSPACE = 0 };
478
Jim Grosbach4a200922013-09-20 23:08:21 +0000479AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
480 const MCAsmInfo &_MAI)
481 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
482 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
483 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
484 ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000485 // Save the old handler.
486 SavedDiagHandler = SrcMgr.getDiagHandler();
487 SavedDiagContext = SrcMgr.getDiagContext();
488 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000489 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000490 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000491
Daniel Dunbare4749702010-07-12 18:12:02 +0000492 // Initialize the platform / file format parser.
493 //
494 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
495 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000496 if (_MAI.hasMicrosoftFastStdCallMangling()) {
497 PlatformParser = createCOFFAsmParser();
498 PlatformParser->Initialize(*this);
499 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000500 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000501 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000502 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000503 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000504 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000505 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000506 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000507
Eli Bendersky6ee13082013-01-15 22:59:42 +0000508 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000509}
510
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000511AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000512 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
513
514 // Destroy any macros.
Jim Grosbach4a200922013-09-20 23:08:21 +0000515 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
516 ie = MacroMap.end();
517 it != ie; ++it)
Daniel Dunbar56491302010-07-29 01:51:55 +0000518 delete it->getValue();
519
Daniel Dunbare4749702010-07-12 18:12:02 +0000520 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000521}
522
Jim Grosbach4a200922013-09-20 23:08:21 +0000523void AsmParser::printMacroInstantiations() {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524 // Print the active macro instantiation stack.
Jim Grosbach4a200922013-09-20 23:08:21 +0000525 for (std::vector<MacroInstantiation *>::const_reverse_iterator
526 it = ActiveMacros.rbegin(),
527 ie = ActiveMacros.rend();
528 it != ie; ++it)
529 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000530 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531}
532
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000533bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000534 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000535 return Error(L, Msg, Ranges);
Jim Grosbach4a200922013-09-20 23:08:21 +0000536 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
537 printMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000538 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000539}
540
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000541bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000542 HadError = true;
Jim Grosbach4a200922013-09-20 23:08:21 +0000543 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
544 printMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000545 return true;
546}
547
Jim Grosbach4a200922013-09-20 23:08:21 +0000548bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000549 std::string IncludedFile;
550 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 if (NewBuf == -1)
552 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000553
Sean Callananfd0b0282010-01-21 00:19:58 +0000554 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000555
Sean Callananfd0b0282010-01-21 00:19:58 +0000556 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000557
Sean Callananfd0b0282010-01-21 00:19:58 +0000558 return false;
559}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000560
Sylvestre Ledruda2ed452013-05-14 23:36:24 +0000561/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000562/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000563/// returns true on failure.
Jim Grosbach4a200922013-09-20 23:08:21 +0000564bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000565 std::string IncludedFile;
566 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
567 if (NewBuf == -1)
568 return true;
569
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000570 // Pick up the bytes from the file and emit them.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +0000571 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000572 return false;
573}
574
Jim Grosbach4a200922013-09-20 23:08:21 +0000575void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000576 if (InBuffer != -1) {
577 CurBuffer = InBuffer;
578 } else {
579 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
580 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000581 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
582}
583
Sean Callananfd0b0282010-01-21 00:19:58 +0000584const AsmToken &AsmParser::Lex() {
585 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000586
Sean Callananfd0b0282010-01-21 00:19:58 +0000587 if (tok->is(AsmToken::Eof)) {
588 // If this is the end of an included file, pop the parent file off the
589 // include stack.
590 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
591 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4a200922013-09-20 23:08:21 +0000592 jumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000593 tok = &Lexer.Lex();
594 }
595 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000596
Sean Callananfd0b0282010-01-21 00:19:58 +0000597 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000598 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000599
Sean Callananfd0b0282010-01-21 00:19:58 +0000600 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000601}
602
Chris Lattner79180e22010-04-05 23:15:42 +0000603bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000604 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000605 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000606 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000607
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000608 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000609 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000610
611 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000612 AsmCond StartingCondState = TheCondState;
613
Kevin Enderby613b7572011-11-01 22:27:22 +0000614 // If we are generating dwarf for assembly source files save the initial text
615 // section and generate a .file directive.
616 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000617 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000618 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
619 getStreamer().EmitLabel(SectionStartSym);
620 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000621 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000622 StringRef(),
623 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000624 }
625
Chris Lattnerb717fb02009-07-02 21:53:43 +0000626 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000627 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000628 ParseStatementInfo Info;
Jim Grosbach4a200922013-09-20 23:08:21 +0000629 if (!parseStatement(Info))
630 continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000632 // 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!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000635 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000636 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000637
638 if (TheCondState.TheCond != StartingCondState.TheCond ||
639 TheCondState.Ignore != StartingCondState.Ignore)
640 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000641
642 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000643 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Jim Grosbach4a200922013-09-20 23:08:21 +0000644 getContext().getMCDwarfFiles();
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000645 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000646 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000647 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000648 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000649
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000650 // 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(),
Jim Grosbach4a200922013-09-20 23:08:21 +0000657 e = Symbols.end();
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000658 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.
Jim Grosbach4a200922013-09-20 23:08:21 +0000667 printMessage(
668 getLexer().getLoc(), SourceMgr::DK_Error,
669 "assembler local symbol '" + Sym->getName() + "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000670 }
671 }
672
Chris Lattner79180e22010-04-05 23:15:42 +0000673 // Finalize the output stream if there are no errors and if the client wants
674 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000675 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000676 Out.Finish();
677
Chris Lattnerb717fb02009-07-02 21:53:43 +0000678 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000679}
680
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000681void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000682 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000683 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000684 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000685 }
686}
687
Jim Grosbach4a200922013-09-20 23:08:21 +0000688/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000689void AsmParser::eatToEndOfStatement() {
Jim Grosbach4a200922013-09-20 23:08:21 +0000690 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000691 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000692
Chris Lattner2cf5f142009-06-22 01:29:09 +0000693 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000694 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000695 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000696}
697
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000698StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000699 const char *Start = getTok().getLoc().getPointer();
700
Jim Grosbach4a200922013-09-20 23:08:21 +0000701 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000702 Lex();
703
704 const char *End = getTok().getLoc().getPointer();
705 return StringRef(Start, End - Start);
706}
Chris Lattnerc4193832009-06-22 05:51:26 +0000707
Jim Grosbach4a200922013-09-20 23:08:21 +0000708StringRef AsmParser::parseStringToComma() {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000709 const char *Start = getTok().getLoc().getPointer();
710
711 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4a200922013-09-20 23:08:21 +0000712 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000713 Lex();
714
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
717}
718
Jim Grosbach4a200922013-09-20 23:08:21 +0000719/// \brief Parse a paren expression and return it.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000720/// NOTE: This assumes the leading '(' has already been consumed.
721///
722/// parenexpr ::= expr)
723///
Jim Grosbach4a200922013-09-20 23:08:21 +0000724bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (parseExpression(Res))
726 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000727 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000728 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000729 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000730 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000731 return false;
732}
Chris Lattnerc4193832009-06-22 05:51:26 +0000733
Jim Grosbach4a200922013-09-20 23:08:21 +0000734/// \brief Parse a bracket expression and return it.
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000735/// NOTE: This assumes the leading '[' has already been consumed.
736///
737/// bracketexpr ::= expr]
738///
Jim Grosbach4a200922013-09-20 23:08:21 +0000739bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
740 if (parseExpression(Res))
741 return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000742 if (Lexer.isNot(AsmToken::RBrac))
743 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000744 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000745 Lex();
746 return false;
747}
748
Jim Grosbach4a200922013-09-20 23:08:21 +0000749/// \brief Parse a primary expression and return it.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000750/// primaryexpr ::= (parenexpr
751/// primaryexpr ::= symbol
752/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000753/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000754/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4a200922013-09-20 23:08:21 +0000755bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000756 SMLoc FirstTokenLoc = getLexer().getLoc();
757 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
758 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000759 default:
760 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000761 // If we have an error assume that we've already handled it.
762 case AsmToken::Error:
763 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000764 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000765 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000766 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000767 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000768 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000769 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000770 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000771 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000772 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000773 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000774 if (parseIdentifier(Identifier)) {
David Majnemer3f22cc12013-09-25 10:47:21 +0000775 if (FirstTokenKind == AsmToken::Dollar) {
776 if (Lexer.getMAI().getDollarIsPC()) {
777 // This is a '$' reference, which references the current PC. Emit a
778 // temporary label to the streamer and refer to it.
779 MCSymbol *Sym = Ctx.CreateTempSymbol();
780 Out.EmitLabel(Sym);
781 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
782 EndLoc = FirstTokenLoc;
783 return false;
784 } else
785 return Error(FirstTokenLoc, "invalid token in expression");
786 return true;
787 }
Kevin Enderby5de048e2013-01-22 21:09:20 +0000788 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000789
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000790 EndLoc = SMLoc::getFromPointer(Identifier.end());
791
Daniel Dunbarfffff912009-10-16 01:34:54 +0000792 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000793 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000794 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795
796 // Lookup the symbol variant if used.
797 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000798 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000799 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000800 if (Variant == MCSymbolRefExpr::VK_Invalid) {
801 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000802 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000803 }
804 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000805
Daniel Dunbarfffff912009-10-16 01:34:54 +0000806 // If this is an absolute variable reference, substitute it now to preserve
807 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000808 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000809 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000810 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000811
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000812 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000813 return false;
814 }
815
816 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000817 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000818 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000819 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000820 case AsmToken::Integer: {
821 SMLoc Loc = getTok().getLoc();
822 int64_t IntVal = getTok().getIntVal();
823 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000824 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000825 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000826 // Look for 'b' or 'f' following an Integer as a directional label
827 if (Lexer.getKind() == AsmToken::Identifier) {
828 StringRef IDVal = getTok().getString();
Ulrich Weigand151ad372013-06-20 16:24:17 +0000829 // Lookup the symbol variant if used.
830 std::pair<StringRef, StringRef> Split = IDVal.split('@');
831 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
832 if (Split.first.size() != IDVal.size()) {
833 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
834 if (Variant == MCSymbolRefExpr::VK_Invalid) {
835 Variant = MCSymbolRefExpr::VK_None;
836 return TokError("invalid variant '" + Split.second + "'");
837 }
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000838 IDVal = Split.first;
Ulrich Weigand151ad372013-06-20 16:24:17 +0000839 }
Jim Grosbach4a200922013-09-20 23:08:21 +0000840 if (IDVal == "f" || IDVal == "b") {
841 MCSymbol *Sym =
842 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
Ulrich Weigand151ad372013-06-20 16:24:17 +0000843 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000844 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000845 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000846 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000847 Lex(); // Eat identifier.
848 }
849 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000850 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000851 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000852 case AsmToken::Real: {
853 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000854 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000855 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000856 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000857 Lex(); // Eat token.
858 return false;
859 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000860 case AsmToken::Dot: {
861 // This is a '.' reference, which references the current PC. Emit a
862 // temporary label to the streamer and refer to it.
863 MCSymbol *Sym = Ctx.CreateTempSymbol();
864 Out.EmitLabel(Sym);
865 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000866 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000867 Lex(); // Eat identifier.
868 return false;
869 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000870 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000871 Lex(); // Eat the '('.
Jim Grosbach4a200922013-09-20 23:08:21 +0000872 return parseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000873 case AsmToken::LBrac:
874 if (!PlatformParser->HasBracketExpressions())
875 return TokError("brackets expression not supported on this target");
876 Lex(); // Eat the '['.
Jim Grosbach4a200922013-09-20 23:08:21 +0000877 return parseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000878 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000879 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000880 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000881 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000882 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000883 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000884 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000885 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000886 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000887 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000888 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000889 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000890 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000891 Lex(); // Eat the operator.
Jim Grosbach4a200922013-09-20 23:08:21 +0000892 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000893 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000894 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000895 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000896 }
897}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000898
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000899bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000900 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000901 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000902}
903
Daniel Dunbarcceba832010-09-17 02:47:07 +0000904const MCExpr *
Jim Grosbach4a200922013-09-20 23:08:21 +0000905AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbarcceba832010-09-17 02:47:07 +0000906 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenberger66b71392013-08-27 20:23:19 +0000907 // Ask the target implementation about this expression first.
908 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
909 if (NewE)
910 return NewE;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000911 // Recurse over the given expression, rebuilding it to apply the given variant
912 // if there is exactly one symbol.
913 switch (E->getKind()) {
914 case MCExpr::Target:
915 case MCExpr::Constant:
916 return 0;
917
918 case MCExpr::SymbolRef: {
919 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
920
921 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4a200922013-09-20 23:08:21 +0000922 TokError("invalid variant on expression '" + getTok().getIdentifier() +
923 "' (already modified)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000924 return E;
925 }
926
927 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
928 }
929
930 case MCExpr::Unary: {
931 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4a200922013-09-20 23:08:21 +0000932 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000933 if (!Sub)
934 return 0;
935 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
936 }
937
938 case MCExpr::Binary: {
939 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4a200922013-09-20 23:08:21 +0000940 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
941 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000942
943 if (!LHS && !RHS)
944 return 0;
945
Jim Grosbach4a200922013-09-20 23:08:21 +0000946 if (!LHS)
947 LHS = BE->getLHS();
948 if (!RHS)
949 RHS = BE->getRHS();
Daniel Dunbarcceba832010-09-17 02:47:07 +0000950
951 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
952 }
953 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000954
Craig Topper85814382012-02-07 05:05:23 +0000955 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000956}
957
Jim Grosbach4a200922013-09-20 23:08:21 +0000958/// \brief Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000959///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000960/// expr ::= expr &&,|| expr -> lowest.
961/// expr ::= expr |,^,&,! expr
962/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
963/// expr ::= expr <<,>> expr
964/// expr ::= expr +,- expr
965/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000966/// expr ::= primaryexpr
967///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000968bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000969 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000970 Res = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +0000971 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000972 return true;
973
Daniel Dunbarcceba832010-09-17 02:47:07 +0000974 // As a special case, we support 'a op b @ modifier' by rewriting the
975 // expression to include the modifier. This is inefficient, but in general we
976 // expect users to use 'a@modifier op b'.
977 if (Lexer.getKind() == AsmToken::At) {
978 Lex();
979
980 if (Lexer.isNot(AsmToken::Identifier))
981 return TokError("unexpected symbol modifier following '@'");
982
983 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4a200922013-09-20 23:08:21 +0000984 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbarcceba832010-09-17 02:47:07 +0000985 if (Variant == MCSymbolRefExpr::VK_Invalid)
986 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
987
Jim Grosbach4a200922013-09-20 23:08:21 +0000988 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000989 if (!ModifiedRes) {
990 return TokError("invalid modifier '" + getTok().getIdentifier() +
991 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000992 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000993
Daniel Dunbarcceba832010-09-17 02:47:07 +0000994 Res = ModifiedRes;
995 Lex();
996 }
997
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000998 // Try to constant fold it up front, if possible.
999 int64_t Value;
1000 if (Res->EvaluateAsAbsolute(Value))
1001 Res = MCConstantExpr::Create(Value, getContext());
1002
1003 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +00001004}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001005
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001006bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +00001007 Res = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00001008 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +00001009}
1010
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001011bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001012 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001013
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001014 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001015 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +00001016 return true;
1017
Daniel Dunbare00b0112009-10-16 01:57:52 +00001018 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001019 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +00001020
1021 return false;
1022}
1023
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001024static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001025 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001026 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001027 default:
Jim Grosbach4a200922013-09-20 23:08:21 +00001028 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001029
Jim Grosbach4a200922013-09-20 23:08:21 +00001030 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001031 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001032 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001033 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001034 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001035 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001036 return 1;
1037
Jim Grosbach4a200922013-09-20 23:08:21 +00001038 // Low Precedence: |, &, ^
1039 //
1040 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001041 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001042 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001043 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001044 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001045 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001046 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001047 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001048 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001049 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001050
Jim Grosbach4a200922013-09-20 23:08:21 +00001051 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001052 case AsmToken::EqualEqual:
1053 Kind = MCBinaryExpr::EQ;
1054 return 3;
1055 case AsmToken::ExclaimEqual:
1056 case AsmToken::LessGreater:
1057 Kind = MCBinaryExpr::NE;
1058 return 3;
1059 case AsmToken::Less:
1060 Kind = MCBinaryExpr::LT;
1061 return 3;
1062 case AsmToken::LessEqual:
1063 Kind = MCBinaryExpr::LTE;
1064 return 3;
1065 case AsmToken::Greater:
1066 Kind = MCBinaryExpr::GT;
1067 return 3;
1068 case AsmToken::GreaterEqual:
1069 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001070 return 3;
1071
Jim Grosbach4a200922013-09-20 23:08:21 +00001072 // Intermediate Precedence: <<, >>
Jim Grosbachfbe16812011-08-20 16:24:13 +00001073 case AsmToken::LessLess:
1074 Kind = MCBinaryExpr::Shl;
1075 return 4;
1076 case AsmToken::GreaterGreater:
1077 Kind = MCBinaryExpr::Shr;
1078 return 4;
1079
Jim Grosbach4a200922013-09-20 23:08:21 +00001080 // High Intermediate Precedence: +, -
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001081 case AsmToken::Plus:
1082 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001083 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001084 case AsmToken::Minus:
1085 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001086 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001087
Jim Grosbach4a200922013-09-20 23:08:21 +00001088 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001089 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001090 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001091 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001092 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001093 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001094 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001095 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001096 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001097 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001098 }
1099}
1100
Jim Grosbach4a200922013-09-20 23:08:21 +00001101/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001102/// Res contains the LHS of the expression on input.
Jim Grosbach4a200922013-09-20 23:08:21 +00001103bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattnerb4307b32010-01-15 19:28:38 +00001104 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001105 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001106 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001107 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001108
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001109 // If the next token is lower precedence than we are allowed to eat, return
1110 // successfully with what we ate already.
1111 if (TokPrec < Precedence)
1112 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001113
Sean Callanan79ed1a82010-01-19 20:22:31 +00001114 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001115
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001116 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001117 const MCExpr *RHS;
Jim Grosbach4a200922013-09-20 23:08:21 +00001118 if (parsePrimaryExpr(RHS, EndLoc))
1119 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001120
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001121 // If BinOp binds less tightly with RHS than the operator after RHS, let
1122 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001123 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001124 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4a200922013-09-20 23:08:21 +00001125 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1126 return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001127
Daniel Dunbar475839e2009-06-29 20:37:27 +00001128 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001129 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001130 }
1131}
1132
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001133/// ParseStatement:
1134/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001135/// ::= Label* Directive ...Operands... EndOfStatement
1136/// ::= Label* Identifier OperandList* EndOfStatement
Jim Grosbach4a200922013-09-20 23:08:21 +00001137bool AsmParser::parseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001138 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001139 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001140 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001141 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001142 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001143
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001144 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001145 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001146 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001147 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001148 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001149 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001150 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4a200922013-09-20 23:08:21 +00001151 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001152
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001153 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001154 if (Lexer.is(AsmToken::Integer)) {
1155 LocalLabelVal = getTok().getIntVal();
1156 if (LocalLabelVal < 0) {
1157 if (!TheCondState.Ignore)
1158 return TokError("unexpected token at start of statement");
1159 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001160 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001161 IDVal = getTok().getString();
1162 Lex(); // Consume the integer token to be used as an identifier token.
1163 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001164 if (!TheCondState.Ignore)
1165 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001166 }
1167 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001168 } else if (Lexer.is(AsmToken::Dot)) {
1169 // Treat '.' as a valid identifier in this context.
1170 Lex();
1171 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001172 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001173 if (!TheCondState.Ignore)
1174 return TokError("unexpected token at start of statement");
1175 IDVal = "";
1176 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001177
Chris Lattner7834fac2010-04-17 18:14:27 +00001178 // Handle conditional assembly here before checking for skipping. We
1179 // have to do this so that .endif isn't skipped in a ".if 0" block for
1180 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001181 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4a200922013-09-20 23:08:21 +00001182 DirectiveKindMap.find(IDVal);
1183 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1184 ? DK_NO_DIRECTIVE
1185 : DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001186 switch (DirKind) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001187 default:
1188 break;
1189 case DK_IF:
1190 return parseDirectiveIf(IDLoc);
1191 case DK_IFB:
1192 return parseDirectiveIfb(IDLoc, true);
1193 case DK_IFNB:
1194 return parseDirectiveIfb(IDLoc, false);
1195 case DK_IFC:
1196 return parseDirectiveIfc(IDLoc, true);
1197 case DK_IFNC:
1198 return parseDirectiveIfc(IDLoc, false);
1199 case DK_IFDEF:
1200 return parseDirectiveIfdef(IDLoc, true);
1201 case DK_IFNDEF:
1202 case DK_IFNOTDEF:
1203 return parseDirectiveIfdef(IDLoc, false);
1204 case DK_ELSEIF:
1205 return parseDirectiveElseIf(IDLoc);
1206 case DK_ELSE:
1207 return parseDirectiveElse(IDLoc);
1208 case DK_ENDIF:
1209 return parseDirectiveEndIf(IDLoc);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001210 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001211
Eli Benderskyed5df012013-01-16 19:32:36 +00001212 // Ignore the statement if in the middle of inactive conditional
1213 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001214 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001215 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001216 return false;
1217 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001218
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001219 // FIXME: Recurse on local labels?
1220
1221 // See what kind of statement we have.
1222 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001223 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001224 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001225
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001226 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001227 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001228
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001229 // Diagnose attempt to use '.' as a label.
1230 if (IDVal == ".")
1231 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1232
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001233 // Diagnose attempt to use a variable as a label.
1234 //
1235 // FIXME: Diagnostics. Note the location of the definition as a label.
1236 // FIXME: This doesn't diagnose assignment to a symbol which has been
1237 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001238 MCSymbol *Sym;
1239 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001240 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001241 else
1242 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001243 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001244 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001245
Daniel Dunbar959fd882009-08-26 22:13:22 +00001246 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001247 if (!ParsingInlineAsm)
1248 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001249
Kevin Enderby94c2e852011-12-09 18:09:40 +00001250 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001251 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001252 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001253 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1254 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001255
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001256 // Consume any end of statement token, if present, to avoid spurious
1257 // AddBlankLine calls().
1258 if (Lexer.is(AsmToken::EndOfStatement)) {
1259 Lex();
1260 if (Lexer.is(AsmToken::Eof))
1261 return false;
1262 }
1263
Eli Friedman2128aae2012-10-22 23:58:19 +00001264 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001265 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001266
Daniel Dunbar3f872332009-07-28 16:08:33 +00001267 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001268 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001269 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001270
Jim Grosbach4a200922013-09-20 23:08:21 +00001271 return parseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001272
1273 default: // Normal instruction or directive.
1274 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001275 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001276
1277 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4a200922013-09-20 23:08:21 +00001278 if (areMacrosEnabled())
1279 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1280 return handleMacroEntry(M, IDLoc);
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001281 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001282
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001283 // Otherwise, we have a normal instruction or directive.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001284
Eli Bendersky6ee13082013-01-15 22:59:42 +00001285 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001286 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001287 // There are several entities interested in parsing directives:
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001288 //
Eli Bendersky6ee13082013-01-15 22:59:42 +00001289 // 1. The target-specific assembly parser. Some directives are target
1290 // specific or may potentially behave differently on certain targets.
1291 // 2. Asm parser extensions. For example, platform-specific parsers
1292 // (like the ELF parser) register themselves as extensions.
1293 // 3. The generic directive parser implemented by this class. These are
1294 // all the directives that behave in a target and platform independent
1295 // manner, or at least have a default behavior that's shared between
1296 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001297
Eli Bendersky6ee13082013-01-15 22:59:42 +00001298 // First query the target-specific parser. It will return 'true' if it
1299 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001300 if (!getTargetParser().ParseDirective(ID))
1301 return false;
1302
Eli Bendersky6ee13082013-01-15 22:59:42 +00001303 // Next, check the extention directive map to see if any extension has
1304 // registered itself to parse this directive.
Jim Grosbach4a200922013-09-20 23:08:21 +00001305 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1306 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky6ee13082013-01-15 22:59:42 +00001307 if (Handler.first)
1308 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1309
1310 // Finally, if no one else is interested in this directive, it must be
1311 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 switch (DirKind) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001313 default:
1314 break;
1315 case DK_SET:
1316 case DK_EQU:
1317 return parseDirectiveSet(IDVal, true);
1318 case DK_EQUIV:
1319 return parseDirectiveSet(IDVal, false);
1320 case DK_ASCII:
1321 return parseDirectiveAscii(IDVal, false);
1322 case DK_ASCIZ:
1323 case DK_STRING:
1324 return parseDirectiveAscii(IDVal, true);
1325 case DK_BYTE:
1326 return parseDirectiveValue(1);
1327 case DK_SHORT:
1328 case DK_VALUE:
1329 case DK_2BYTE:
1330 return parseDirectiveValue(2);
1331 case DK_LONG:
1332 case DK_INT:
1333 case DK_4BYTE:
1334 return parseDirectiveValue(4);
1335 case DK_QUAD:
1336 case DK_8BYTE:
1337 return parseDirectiveValue(8);
1338 case DK_SINGLE:
1339 case DK_FLOAT:
1340 return parseDirectiveRealValue(APFloat::IEEEsingle);
1341 case DK_DOUBLE:
1342 return parseDirectiveRealValue(APFloat::IEEEdouble);
1343 case DK_ALIGN: {
1344 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1345 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1346 }
1347 case DK_ALIGN32: {
1348 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1349 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1350 }
1351 case DK_BALIGN:
1352 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1353 case DK_BALIGNW:
1354 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1355 case DK_BALIGNL:
1356 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1357 case DK_P2ALIGN:
1358 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1359 case DK_P2ALIGNW:
1360 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1361 case DK_P2ALIGNL:
1362 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1363 case DK_ORG:
1364 return parseDirectiveOrg();
1365 case DK_FILL:
1366 return parseDirectiveFill();
1367 case DK_ZERO:
1368 return parseDirectiveZero();
1369 case DK_EXTERN:
1370 eatToEndOfStatement(); // .extern is the default, ignore it.
1371 return false;
1372 case DK_GLOBL:
1373 case DK_GLOBAL:
1374 return parseDirectiveSymbolAttribute(MCSA_Global);
1375 case DK_LAZY_REFERENCE:
1376 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1377 case DK_NO_DEAD_STRIP:
1378 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1379 case DK_SYMBOL_RESOLVER:
1380 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1381 case DK_PRIVATE_EXTERN:
1382 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1383 case DK_REFERENCE:
1384 return parseDirectiveSymbolAttribute(MCSA_Reference);
1385 case DK_WEAK_DEFINITION:
1386 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1387 case DK_WEAK_REFERENCE:
1388 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1389 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1390 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1391 case DK_COMM:
1392 case DK_COMMON:
1393 return parseDirectiveComm(/*IsLocal=*/false);
1394 case DK_LCOMM:
1395 return parseDirectiveComm(/*IsLocal=*/true);
1396 case DK_ABORT:
1397 return parseDirectiveAbort();
1398 case DK_INCLUDE:
1399 return parseDirectiveInclude();
1400 case DK_INCBIN:
1401 return parseDirectiveIncbin();
1402 case DK_CODE16:
1403 case DK_CODE16GCC:
1404 return TokError(Twine(IDVal) + " not supported yet");
1405 case DK_REPT:
1406 return parseDirectiveRept(IDLoc);
1407 case DK_IRP:
1408 return parseDirectiveIrp(IDLoc);
1409 case DK_IRPC:
1410 return parseDirectiveIrpc(IDLoc);
1411 case DK_ENDR:
1412 return parseDirectiveEndr(IDLoc);
1413 case DK_BUNDLE_ALIGN_MODE:
1414 return parseDirectiveBundleAlignMode();
1415 case DK_BUNDLE_LOCK:
1416 return parseDirectiveBundleLock();
1417 case DK_BUNDLE_UNLOCK:
1418 return parseDirectiveBundleUnlock();
1419 case DK_SLEB128:
1420 return parseDirectiveLEB128(true);
1421 case DK_ULEB128:
1422 return parseDirectiveLEB128(false);
1423 case DK_SPACE:
1424 case DK_SKIP:
1425 return parseDirectiveSpace(IDVal);
1426 case DK_FILE:
1427 return parseDirectiveFile(IDLoc);
1428 case DK_LINE:
1429 return parseDirectiveLine();
1430 case DK_LOC:
1431 return parseDirectiveLoc();
1432 case DK_STABS:
1433 return parseDirectiveStabs();
1434 case DK_CFI_SECTIONS:
1435 return parseDirectiveCFISections();
1436 case DK_CFI_STARTPROC:
1437 return parseDirectiveCFIStartProc();
1438 case DK_CFI_ENDPROC:
1439 return parseDirectiveCFIEndProc();
1440 case DK_CFI_DEF_CFA:
1441 return parseDirectiveCFIDefCfa(IDLoc);
1442 case DK_CFI_DEF_CFA_OFFSET:
1443 return parseDirectiveCFIDefCfaOffset();
1444 case DK_CFI_ADJUST_CFA_OFFSET:
1445 return parseDirectiveCFIAdjustCfaOffset();
1446 case DK_CFI_DEF_CFA_REGISTER:
1447 return parseDirectiveCFIDefCfaRegister(IDLoc);
1448 case DK_CFI_OFFSET:
1449 return parseDirectiveCFIOffset(IDLoc);
1450 case DK_CFI_REL_OFFSET:
1451 return parseDirectiveCFIRelOffset(IDLoc);
1452 case DK_CFI_PERSONALITY:
1453 return parseDirectiveCFIPersonalityOrLsda(true);
1454 case DK_CFI_LSDA:
1455 return parseDirectiveCFIPersonalityOrLsda(false);
1456 case DK_CFI_REMEMBER_STATE:
1457 return parseDirectiveCFIRememberState();
1458 case DK_CFI_RESTORE_STATE:
1459 return parseDirectiveCFIRestoreState();
1460 case DK_CFI_SAME_VALUE:
1461 return parseDirectiveCFISameValue(IDLoc);
1462 case DK_CFI_RESTORE:
1463 return parseDirectiveCFIRestore(IDLoc);
1464 case DK_CFI_ESCAPE:
1465 return parseDirectiveCFIEscape();
1466 case DK_CFI_SIGNAL_FRAME:
1467 return parseDirectiveCFISignalFrame();
1468 case DK_CFI_UNDEFINED:
1469 return parseDirectiveCFIUndefined(IDLoc);
1470 case DK_CFI_REGISTER:
1471 return parseDirectiveCFIRegister(IDLoc);
1472 case DK_MACROS_ON:
1473 case DK_MACROS_OFF:
1474 return parseDirectiveMacrosOnOff(IDVal);
1475 case DK_MACRO:
1476 return parseDirectiveMacro(IDLoc);
1477 case DK_ENDM:
1478 case DK_ENDMACRO:
1479 return parseDirectiveEndMacro(IDVal);
1480 case DK_PURGEM:
1481 return parseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001482 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001483
Jim Grosbach686c0182012-05-01 18:38:27 +00001484 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001485 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001486
Chad Rosier469b1442013-02-12 21:33:51 +00001487 // __asm _emit or __asm __emit
1488 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1489 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4a200922013-09-20 23:08:21 +00001490 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosier469b1442013-02-12 21:33:51 +00001491
1492 // __asm align
1493 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4a200922013-09-20 23:08:21 +00001494 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001495
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001496 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001497
Chris Lattnera7f13542010-05-19 23:34:33 +00001498 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001499 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001500 ParseInstructionInfo IInfo(Info.AsmRewrites);
Jim Grosbach4a200922013-09-20 23:08:21 +00001501 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001502 Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001503 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001504
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001505 // Dump the parsed representation, if requested.
1506 if (getShowParsedOperands()) {
1507 SmallString<256> Str;
1508 raw_svector_ostream OS(Str);
1509 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001510 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001511 if (i != 0)
1512 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001513 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001514 }
1515 OS << "]";
1516
Jim Grosbach4a200922013-09-20 23:08:21 +00001517 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001518 }
1519
Kevin Enderby613b7572011-11-01 22:27:22 +00001520 // If we are generating dwarf for assembly source files and the current
1521 // section is the initial text section then generate a .loc directive for
1522 // the instruction.
1523 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001524 getContext().getGenDwarfSection() ==
Jim Grosbach4a200922013-09-20 23:08:21 +00001525 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001526
Eli Benderskyed5df012013-01-16 19:32:36 +00001527 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001528
Eli Benderskyed5df012013-01-16 19:32:36 +00001529 // If we previously parsed a cpp hash file line comment then make sure the
1530 // current Dwarf File is for the CppHashFilename if not then emit the
1531 // Dwarf File table for it and adjust the line number for the .loc.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001532 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Jim Grosbach4a200922013-09-20 23:08:21 +00001533 getContext().getMCDwarfFiles();
Eli Benderskyed5df012013-01-16 19:32:36 +00001534 if (CppHashFilename.size() != 0) {
1535 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001536 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001537 getStreamer().EmitDwarfFileDirective(
Jim Grosbach4a200922013-09-20 23:08:21 +00001538 getContext().nextGenDwarfFileNumber(), StringRef(),
1539 CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001540
Jim Grosbach4a200922013-09-20 23:08:21 +00001541 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1542 // cache with the different Loc from the call above we save the last
1543 // info we queried here with SrcMgr.FindLineNumber().
1544 unsigned CppHashLocLineNo;
1545 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1546 CppHashLocLineNo = LastQueryLine;
1547 else {
1548 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1549 LastQueryLine = CppHashLocLineNo;
1550 LastQueryIDLoc = CppHashLoc;
1551 LastQueryBuffer = CppHashBuf;
1552 }
1553 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001554 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001555
Jim Grosbach4a200922013-09-20 23:08:21 +00001556 getStreamer().EmitDwarfLocDirective(
1557 getContext().getGenDwarfFileNumber(), Line, 0,
1558 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1559 StringRef());
Kevin Enderby613b7572011-11-01 22:27:22 +00001560 }
1561
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001562 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001563 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001564 unsigned ErrorInfo;
Jim Grosbach4a200922013-09-20 23:08:21 +00001565 HadError = getTargetParser().MatchAndEmitInstruction(
1566 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1567 ParsingInlineAsm);
Chad Rosier84125ca2012-10-13 00:26:04 +00001568 }
Chris Lattner98986712010-01-14 22:21:20 +00001569
Chris Lattnercbf8a982010-09-11 16:18:25 +00001570 // Don't skip the rest of the line, the instruction parser is responsible for
1571 // that.
1572 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001573}
Chris Lattner9a023f72009-06-24 04:43:34 +00001574
Jim Grosbach4a200922013-09-20 23:08:21 +00001575/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001576/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4a200922013-09-20 23:08:21 +00001577void AsmParser::eatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001578 if (!Lexer.is(AsmToken::EndOfStatement))
1579 Lexer.LexUntilEndOfLine();
Jim Grosbach4a200922013-09-20 23:08:21 +00001580 // Eat EOL.
1581 Lex();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001582}
1583
Jim Grosbach4a200922013-09-20 23:08:21 +00001584/// parseCppHashLineFilenameComment as this:
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001585/// ::= # number "filename"
1586/// or just as a full line comment if it doesn't have a number and a string.
Jim Grosbach4a200922013-09-20 23:08:21 +00001587bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001588 Lex(); // Eat the hash token.
1589
1590 if (getLexer().isNot(AsmToken::Integer)) {
1591 // Consume the line since in cases it is not a well-formed line directive,
1592 // as if were simply a full line comment.
Jim Grosbach4a200922013-09-20 23:08:21 +00001593 eatToEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001594 return false;
1595 }
1596
1597 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001598 Lex();
1599
1600 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001601 eatToEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001602 return false;
1603 }
1604
1605 StringRef Filename = getTok().getString();
1606 // Get rid of the enclosing quotes.
Jim Grosbach4a200922013-09-20 23:08:21 +00001607 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001608
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001609 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1610 CppHashLoc = L;
1611 CppHashFilename = Filename;
1612 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001613 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001614
1615 // Ignore any trailing characters, they're just comment.
Jim Grosbach4a200922013-09-20 23:08:21 +00001616 eatToEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001617 return false;
1618}
1619
Jim Grosbach4a200922013-09-20 23:08:21 +00001620/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001621/// for the Filename and LineNo if any in the diagnostic.
1622void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001623 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001624 raw_ostream &OS = errs();
1625
1626 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1627 const SMLoc &DiagLoc = Diag.getLoc();
1628 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1629 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1630
Jim Grosbach4a200922013-09-20 23:08:21 +00001631 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001632 // before printing the message.
1633 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001634 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001635 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1636 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001637 }
1638
Eric Christopher2318ba12012-12-18 00:30:54 +00001639 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001640 // manager changed or buffer changed (like in a nested include) then just
1641 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4a200922013-09-20 23:08:21 +00001642 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001643 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001644 if (Parser->SavedDiagHandler)
1645 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1646 else
1647 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001648 return;
1649 }
1650
Eric Christopher2318ba12012-12-18 00:30:54 +00001651 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001652 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1653 // the diagnostic.
Jakub Staszakb06ea252013-09-16 22:03:38 +00001654 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001655
1656 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1657 int CppHashLocLineNo =
1658 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4a200922013-09-20 23:08:21 +00001659 int LineNo =
1660 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001661
Jim Grosbach4a200922013-09-20 23:08:21 +00001662 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1663 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001664 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001665
Benjamin Kramer04a04262011-10-16 10:48:29 +00001666 if (Parser->SavedDiagHandler)
1667 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1668 else
1669 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001670}
1671
Rafael Espindola799aacf2012-08-21 18:29:30 +00001672// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1673// difference being that that function accepts '@' as part of identifiers and
1674// we can't do that. AsmLexer.cpp should probably be changed to handle
1675// '@' as a special case when needed.
1676static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001677 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1678 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001679}
1680
Rafael Espindola761cb062012-06-03 23:57:14 +00001681bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001682 const MCAsmMacroParameters &Parameters,
Jim Grosbach4a200922013-09-20 23:08:21 +00001683 const MCAsmMacroArguments &A, const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001684 unsigned NParameters = Parameters.size();
1685 if (NParameters != 0 && NParameters != A.size())
1686 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001687
Preston Gurd7b6f2032012-09-19 20:36:12 +00001688 // A macro without parameters is handled differently on Darwin:
1689 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001690 while (!Body.empty()) {
1691 // Scan for the next substitution.
1692 std::size_t End = Body.size(), Pos = 0;
1693 for (; Pos != End; ++Pos) {
1694 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001695 if (!NParameters) {
1696 // This macro has no parameters, look for $0, $1, etc.
1697 if (Body[Pos] != '$' || Pos + 1 == End)
1698 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001699
Rafael Espindola65366442011-06-05 02:43:45 +00001700 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001701 if (Next == '$' || Next == 'n' ||
1702 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001703 break;
1704 } else {
1705 // This macro has parameters, look for \foo, \bar, etc.
1706 if (Body[Pos] == '\\' && Pos + 1 != End)
1707 break;
1708 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001709 }
1710
1711 // Add the prefix.
1712 OS << Body.slice(0, Pos);
1713
1714 // Check if we reached the end.
1715 if (Pos == End)
1716 break;
1717
Rafael Espindola65366442011-06-05 02:43:45 +00001718 if (!NParameters) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001719 switch (Body[Pos + 1]) {
1720 // $$ => $
Rafael Espindola65366442011-06-05 02:43:45 +00001721 case '$':
1722 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001723 break;
1724
Jim Grosbach4a200922013-09-20 23:08:21 +00001725 // $n => number of arguments
Rafael Espindola65366442011-06-05 02:43:45 +00001726 case 'n':
1727 OS << A.size();
1728 break;
1729
Jim Grosbach4a200922013-09-20 23:08:21 +00001730 // $[0-9] => argument
Rafael Espindola65366442011-06-05 02:43:45 +00001731 default: {
1732 // Missing arguments are ignored.
Jim Grosbach4a200922013-09-20 23:08:21 +00001733 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola65366442011-06-05 02:43:45 +00001734 if (Index >= A.size())
1735 break;
1736
1737 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001738 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4a200922013-09-20 23:08:21 +00001739 ie = A[Index].end();
1740 it != ie; ++it)
Rafael Espindola65366442011-06-05 02:43:45 +00001741 OS << it->getString();
1742 break;
1743 }
1744 }
1745 Pos += 2;
1746 } else {
1747 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001748 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001749 ++I;
1750
Jim Grosbach4a200922013-09-20 23:08:21 +00001751 const char *Begin = Body.data() + Pos + 1;
1752 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola65366442011-06-05 02:43:45 +00001753 unsigned Index = 0;
1754 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001755 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001756 break;
1757
Preston Gurd7b6f2032012-09-19 20:36:12 +00001758 if (Index == NParameters) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001759 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1760 Pos += 3;
1761 else {
1762 OS << '\\' << Argument;
1763 Pos = I;
1764 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001765 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001766 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4a200922013-09-20 23:08:21 +00001767 ie = A[Index].end();
1768 it != ie; ++it)
Preston Gurd7b6f2032012-09-19 20:36:12 +00001769 if (it->getKind() == AsmToken::String)
1770 OS << it->getStringContents();
1771 else
1772 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001773
Preston Gurd7b6f2032012-09-19 20:36:12 +00001774 Pos += 1 + Argument.size();
1775 }
Rafael Espindola65366442011-06-05 02:43:45 +00001776 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001777 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001778 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001779 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001780
Rafael Espindola65366442011-06-05 02:43:45 +00001781 return false;
1782}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001783
Jim Grosbach4a200922013-09-20 23:08:21 +00001784MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1785 SMLoc EL, MemoryBuffer *I)
1786 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1787 ExitLoc(EL) {}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001788
Jim Grosbach4a200922013-09-20 23:08:21 +00001789static bool isOperator(AsmToken::TokenKind kind) {
1790 switch (kind) {
1791 default:
1792 return false;
1793 case AsmToken::Plus:
1794 case AsmToken::Minus:
1795 case AsmToken::Tilde:
1796 case AsmToken::Slash:
1797 case AsmToken::Star:
1798 case AsmToken::Dot:
1799 case AsmToken::Equal:
1800 case AsmToken::EqualEqual:
1801 case AsmToken::Pipe:
1802 case AsmToken::PipePipe:
1803 case AsmToken::Caret:
1804 case AsmToken::Amp:
1805 case AsmToken::AmpAmp:
1806 case AsmToken::Exclaim:
1807 case AsmToken::ExclaimEqual:
1808 case AsmToken::Percent:
1809 case AsmToken::Less:
1810 case AsmToken::LessEqual:
1811 case AsmToken::LessLess:
1812 case AsmToken::LessGreater:
1813 case AsmToken::Greater:
1814 case AsmToken::GreaterEqual:
1815 case AsmToken::GreaterGreater:
1816 return true;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001817 }
1818}
1819
Jim Grosbach4a200922013-09-20 23:08:21 +00001820bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001821 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001822 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001823 unsigned AddTokens = 0;
1824
1825 // gas accepts arguments separated by whitespace, except on Darwin
1826 if (!IsDarwin)
1827 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001828
1829 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001830 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1831 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001832 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001833 }
1834
1835 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1836 // Spaces and commas cannot be mixed to delimit parameters
1837 if (ArgumentDelimiter == AsmToken::Eof)
1838 ArgumentDelimiter = AsmToken::Comma;
1839 else if (ArgumentDelimiter != AsmToken::Comma) {
1840 Lexer.setSkipSpace(true);
1841 return TokError("expected ' ' for macro argument separator");
1842 }
1843 break;
1844 }
1845
1846 if (Lexer.is(AsmToken::Space)) {
1847 Lex(); // Eat spaces
1848
1849 // Spaces can delimit parameters, but could also be part an expression.
1850 // If the token after a space is an operator, add the token and the next
1851 // one into this argument
1852 if (ArgumentDelimiter == AsmToken::Space ||
1853 ArgumentDelimiter == AsmToken::Eof) {
Jim Grosbach4a200922013-09-20 23:08:21 +00001854 if (isOperator(Lexer.getKind())) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001855 // Check to see whether the token is used as an operator,
1856 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001857 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001858 if (*NextChar == ' ')
1859 AddTokens = 2;
1860 }
1861
1862 if (!AddTokens && ParenLevel == 0) {
1863 if (ArgumentDelimiter == AsmToken::Eof &&
Jim Grosbach4a200922013-09-20 23:08:21 +00001864 !isOperator(Lexer.getKind()))
Preston Gurd7b6f2032012-09-19 20:36:12 +00001865 ArgumentDelimiter = AsmToken::Space;
1866 break;
1867 }
1868 }
1869 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001870
Jim Grosbach4a200922013-09-20 23:08:21 +00001871 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001872 // to be able to fill in the remaining default parameter values
1873 if (Lexer.is(AsmToken::EndOfStatement))
1874 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001875
1876 // Adjust the current parentheses level.
1877 if (Lexer.is(AsmToken::LParen))
1878 ++ParenLevel;
1879 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1880 --ParenLevel;
1881
1882 // Append the token to the current argument list.
1883 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001884 if (AddTokens)
1885 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001886 Lex();
1887 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001888
1889 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001890 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001891 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001892 return false;
1893}
1894
1895// Parse the macro instantiation arguments.
Jim Grosbach4a200922013-09-20 23:08:21 +00001896bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001897 MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001898 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001899 // Argument delimiter is initially unknown. It will be set by
Jim Grosbach4a200922013-09-20 23:08:21 +00001900 // parseMacroArgument()
Preston Gurd7b6f2032012-09-19 20:36:12 +00001901 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001902
1903 // Parse two kinds of macro invocations:
1904 // - macros defined without any parameters accept an arbitrary number of them
1905 // - macros defined with parameters accept at most that many of them
1906 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1907 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001908 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001909
Jim Grosbach4a200922013-09-20 23:08:21 +00001910 if (parseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001911 return true;
1912
Preston Gurd6c9176a2012-09-19 20:29:04 +00001913 if (!MA.empty() || !NParameters)
1914 A.push_back(MA);
1915 else if (NParameters) {
1916 if (!M->Parameters[Parameter].second.empty())
1917 A.push_back(M->Parameters[Parameter].second);
1918 }
Jim Grosbach97146442012-07-30 22:44:17 +00001919
Preston Gurd6c9176a2012-09-19 20:29:04 +00001920 // At the end of the statement, fill in remaining arguments that have
1921 // default values. If there aren't any, then the next argument is
1922 // required but missing
1923 if (Lexer.is(AsmToken::EndOfStatement)) {
1924 if (NParameters && Parameter < NParameters - 1) {
1925 if (M->Parameters[Parameter + 1].second.empty())
1926 return TokError("macro argument '" +
1927 Twine(M->Parameters[Parameter + 1].first) +
1928 "' is missing");
1929 else
1930 continue;
1931 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001932 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001933 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001934
1935 if (Lexer.is(AsmToken::Comma))
1936 Lex();
1937 }
1938 return TokError("Too many arguments");
1939}
1940
Jim Grosbach4a200922013-09-20 23:08:21 +00001941const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1942 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001943 return (I == MacroMap.end()) ? NULL : I->getValue();
1944}
1945
Jim Grosbach4a200922013-09-20 23:08:21 +00001946void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001947 MacroMap[Name] = new MCAsmMacro(Macro);
1948}
1949
Jim Grosbach4a200922013-09-20 23:08:21 +00001950void AsmParser::undefineMacro(StringRef Name) {
1951 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001952 if (I != MacroMap.end()) {
1953 delete I->getValue();
1954 MacroMap.erase(I);
1955 }
1956}
1957
Jim Grosbach4a200922013-09-20 23:08:21 +00001958bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001959 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1960 // this, although we should protect against infinite loops.
1961 if (ActiveMacros.size() == 20)
1962 return TokError("macros cannot be nested more than 20 levels deep");
1963
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001964 MCAsmMacroArguments A;
Jim Grosbach4a200922013-09-20 23:08:21 +00001965 if (parseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001966 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001967
Jim Grosbach97146442012-07-30 22:44:17 +00001968 // Remove any trailing empty arguments. Do this after-the-fact as we have
1969 // to keep empty arguments in the middle of the list or positionality
1970 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001971 while (!A.empty() && A.back().empty())
1972 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001973
Rafael Espindola65366442011-06-05 02:43:45 +00001974 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1975 // to hold the macro body with substitutions.
1976 SmallString<256> Buf;
1977 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001978 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001979
Rafael Espindola8a403d32012-08-08 14:51:03 +00001980 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001981 return true;
1982
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001983 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001984 // instantiation.
1985 OS << ".endmacro\n";
1986
Rafael Espindola65366442011-06-05 02:43:45 +00001987 MemoryBuffer *Instantiation =
Jim Grosbach4a200922013-09-20 23:08:21 +00001988 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001989
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001990 // Create the macro instantiation object and add to the current macro
1991 // instantiation stack.
Jim Grosbach4a200922013-09-20 23:08:21 +00001992 MacroInstantiation *MI = new MacroInstantiation(
1993 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001994 ActiveMacros.push_back(MI);
1995
1996 // Jump to the macro instantiation and prime the lexer.
1997 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1998 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1999 Lex();
2000
2001 return false;
2002}
2003
Jim Grosbach4a200922013-09-20 23:08:21 +00002004void AsmParser::handleMacroExit() {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002005 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4a200922013-09-20 23:08:21 +00002006 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002007 Lex();
2008
2009 // Pop the instantiation entry.
2010 delete ActiveMacros.back();
2011 ActiveMacros.pop_back();
2012}
2013
Jim Grosbach4a200922013-09-20 23:08:21 +00002014static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002015 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00002016 case MCExpr::Binary: {
Jim Grosbach4a200922013-09-20 23:08:21 +00002017 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2018 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002019 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00002020 case MCExpr::Target:
2021 case MCExpr::Constant:
2022 return false;
2023 case MCExpr::SymbolRef: {
Jim Grosbach4a200922013-09-20 23:08:21 +00002024 const MCSymbol &S =
2025 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002026 if (S.isVariable())
Jim Grosbach4a200922013-09-20 23:08:21 +00002027 return isUsedIn(Sym, S.getVariableValue());
Rafael Espindola8b01c822012-01-28 06:22:14 +00002028 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002029 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002030 case MCExpr::Unary:
Jim Grosbach4a200922013-09-20 23:08:21 +00002031 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002032 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002033
2034 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002035}
2036
Jim Grosbach4a200922013-09-20 23:08:21 +00002037bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002038 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002039 // FIXME: Use better location, we should use proper tokens.
2040 SMLoc EqualLoc = Lexer.getLoc();
2041
Daniel Dunbar821e3332009-08-31 08:09:28 +00002042 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002043 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002044 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002045
Rafael Espindolae71cc862012-01-28 05:57:00 +00002046 // Note: we don't count b as used in "a = b". This is to allow
2047 // a = b
2048 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002049
Daniel Dunbar3f872332009-07-28 16:08:33 +00002050 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002051 return TokError("unexpected token in assignment");
2052
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002053 // Error on assignment to '.'.
2054 if (Name == ".") {
2055 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2056 "(use '.space' or '.org').)"));
2057 }
2058
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002059 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002060 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002061
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002062 // Validate that the LHS is allowed to be a variable (either it has not been
2063 // used as a symbol, or it is an absolute symbol).
2064 MCSymbol *Sym = getContext().LookupSymbol(Name);
2065 if (Sym) {
2066 // Diagnose assignment to a label.
2067 //
2068 // FIXME: Diagnostics. Note the location of the definition as a label.
2069 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Jim Grosbach4a200922013-09-20 23:08:21 +00002070 if (isUsedIn(Sym, Value))
Rafael Espindolae71cc862012-01-28 05:57:00 +00002071 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2072 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002073 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002074 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2075 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002076 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002077 return Error(EqualLoc, "redefinition of '" + Name + "'");
2078 else if (!Sym->isVariable())
2079 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002080 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002081 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
Jim Grosbach4a200922013-09-20 23:08:21 +00002082 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002083
2084 // Don't count these checks as uses.
2085 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002086 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002087 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002088
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002089 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002090
2091 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002092 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002093 if (NoDeadStrip)
2094 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2095
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002096 return false;
2097}
2098
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002099/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002100/// ::= identifier
2101/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002102bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002103 // The assembler has relaxed rules for accepting identifiers, in particular we
2104 // allow things like '.globl $foo', which would normally be separate
2105 // tokens. At this level, we have already lexed so we cannot (currently)
2106 // handle this as a context dependent token, instead we detect adjacent tokens
2107 // and return the combined identifier.
2108 if (Lexer.is(AsmToken::Dollar)) {
2109 SMLoc DollarLoc = getLexer().getLoc();
2110
2111 // Consume the dollar sign, and check for a following identifier.
2112 Lex();
2113 if (Lexer.isNot(AsmToken::Identifier))
2114 return true;
2115
2116 // We have a '$' followed by an identifier, make sure they are adjacent.
2117 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2118 return true;
2119
2120 // Construct the joined identifier and consume the token.
Jim Grosbach4a200922013-09-20 23:08:21 +00002121 Res =
2122 StringRef(DollarLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002123 Lex();
2124 return false;
2125 }
2126
Jim Grosbach4a200922013-09-20 23:08:21 +00002127 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002128 return true;
2129
Sean Callanan18b83232010-01-19 21:44:56 +00002130 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002131
Sean Callanan79ed1a82010-01-19 20:22:31 +00002132 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002133
2134 return false;
2135}
2136
Jim Grosbach4a200922013-09-20 23:08:21 +00002137/// parseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002138/// ::= .equ identifier ',' expression
2139/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002140/// ::= .set identifier ',' expression
Jim Grosbach4a200922013-09-20 23:08:21 +00002141bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002142 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002143
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002144 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002145 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002146
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002147 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002148 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002149 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002150
Jim Grosbach4a200922013-09-20 23:08:21 +00002151 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002152}
2153
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002154bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002155 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002156
2157 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002158 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002159 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2160 if (Str[i] != '\\') {
2161 Data += Str[i];
2162 continue;
2163 }
2164
2165 // Recognize escaped characters. Note that this escape semantics currently
2166 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2167 ++i;
2168 if (i == e)
2169 return TokError("unexpected backslash at end of string");
2170
2171 // Recognize octal sequences.
Jim Grosbach4a200922013-09-20 23:08:21 +00002172 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002173 // Consume up to three octal characters.
2174 unsigned Value = Str[i] - '0';
2175
Jim Grosbach4a200922013-09-20 23:08:21 +00002176 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002177 ++i;
2178 Value = Value * 8 + (Str[i] - '0');
2179
Jim Grosbach4a200922013-09-20 23:08:21 +00002180 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002181 ++i;
2182 Value = Value * 8 + (Str[i] - '0');
2183 }
2184 }
2185
2186 if (Value > 255)
2187 return TokError("invalid octal escape sequence (out of range)");
2188
Jim Grosbach4a200922013-09-20 23:08:21 +00002189 Data += (unsigned char)Value;
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002190 continue;
2191 }
2192
2193 // Otherwise recognize individual escapes.
2194 switch (Str[i]) {
2195 default:
2196 // Just reject invalid escape sequences for now.
2197 return TokError("invalid escape sequence (unrecognized character)");
2198
2199 case 'b': Data += '\b'; break;
2200 case 'f': Data += '\f'; break;
2201 case 'n': Data += '\n'; break;
2202 case 'r': Data += '\r'; break;
2203 case 't': Data += '\t'; break;
2204 case '"': Data += '"'; break;
2205 case '\\': Data += '\\'; break;
2206 }
2207 }
2208
2209 return false;
2210}
2211
Jim Grosbach4a200922013-09-20 23:08:21 +00002212/// parseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002213/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002214bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002216 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002217
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002219 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002220 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002222 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002223 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002224 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002225
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002226 getStreamer().EmitBytes(Data);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 if (ZeroTerminated)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002228 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229
Sean Callanan79ed1a82010-01-19 20:22:31 +00002230 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231
2232 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233 break;
2234
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002235 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002236 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002237 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 }
2239 }
2240
Sean Callanan79ed1a82010-01-19 20:22:31 +00002241 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002242 return false;
2243}
2244
Jim Grosbach4a200922013-09-20 23:08:21 +00002245/// parseDirectiveValue
Daniel Dunbara0d14262009-06-24 23:30:00 +00002246/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002247bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002248 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002249 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002250
Daniel Dunbara0d14262009-06-24 23:30:00 +00002251 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002252 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002253 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002254 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002255 return true;
2256
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002257 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002258 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2259 assert(Size <= 8 && "Invalid size");
2260 uint64_t IntValue = MCE->getValue();
2261 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2262 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002263 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach254cf032011-06-29 16:05:14 +00002264 } else
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002265 getStreamer().EmitValue(Value, Size);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002266
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002267 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002268 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002269
Daniel Dunbara0d14262009-06-24 23:30:00 +00002270 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002271 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002272 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002273 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 }
2275 }
2276
Sean Callanan79ed1a82010-01-19 20:22:31 +00002277 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002278 return false;
2279}
2280
Jim Grosbach4a200922013-09-20 23:08:21 +00002281/// parseDirectiveRealValue
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002282/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002283bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002284 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002285 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002286
2287 for (;;) {
2288 // We don't truly support arithmetic on floating point expressions, so we
2289 // have to manually parse unary prefixes.
2290 bool IsNeg = false;
2291 if (getLexer().is(AsmToken::Minus)) {
2292 Lex();
2293 IsNeg = true;
2294 } else if (getLexer().is(AsmToken::Plus))
2295 Lex();
2296
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002297 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002298 getLexer().isNot(AsmToken::Real) &&
2299 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002300 return TokError("unexpected token in directive");
2301
2302 // Convert to an APFloat.
2303 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002304 StringRef IDVal = getTok().getString();
2305 if (getLexer().is(AsmToken::Identifier)) {
2306 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2307 Value = APFloat::getInf(Semantics);
2308 else if (!IDVal.compare_lower("nan"))
2309 Value = APFloat::getNaN(Semantics, false, ~0);
2310 else
2311 return TokError("invalid floating point literal");
2312 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4a200922013-09-20 23:08:21 +00002313 APFloat::opInvalidOp)
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002314 return TokError("invalid floating point literal");
2315 if (IsNeg)
2316 Value.changeSign();
2317
2318 // Consume the numeric token.
2319 Lex();
2320
2321 // Emit the value as an integer.
2322 APInt AsInt = Value.bitcastToAPInt();
2323 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002324 AsInt.getBitWidth() / 8);
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002325
2326 if (getLexer().is(AsmToken::EndOfStatement))
2327 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002328
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002329 if (getLexer().isNot(AsmToken::Comma))
2330 return TokError("unexpected token in directive");
2331 Lex();
2332 }
2333 }
2334
2335 Lex();
2336 return false;
2337}
2338
Jim Grosbach4a200922013-09-20 23:08:21 +00002339/// parseDirectiveZero
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002340/// ::= .zero expression
Jim Grosbach4a200922013-09-20 23:08:21 +00002341bool AsmParser::parseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002342 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002343
2344 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002345 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002346 return true;
2347
Rafael Espindolae452b172010-10-05 19:42:57 +00002348 int64_t Val = 0;
2349 if (getLexer().is(AsmToken::Comma)) {
2350 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002351 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002352 return true;
2353 }
2354
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002355 if (getLexer().isNot(AsmToken::EndOfStatement))
2356 return TokError("unexpected token in '.zero' directive");
2357
2358 Lex();
2359
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002360 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002361
2362 return false;
2363}
2364
Jim Grosbach4a200922013-09-20 23:08:21 +00002365/// parseDirectiveFill
Roman Divacky9c607102013-09-24 17:44:41 +00002366/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002367bool AsmParser::parseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002368 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002369
Daniel Dunbara0d14262009-06-24 23:30:00 +00002370 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002371 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002372 return true;
2373
Roman Divacky9c607102013-09-24 17:44:41 +00002374 int64_t FillSize = 1;
2375 int64_t FillExpr = 0;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002376
Roman Divacky9c607102013-09-24 17:44:41 +00002377 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2378 if (getLexer().isNot(AsmToken::Comma))
2379 return TokError("unexpected token in '.fill' directive");
2380 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002381
Roman Divacky9c607102013-09-24 17:44:41 +00002382 if (parseAbsoluteExpression(FillSize))
2383 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002384
Roman Divacky9c607102013-09-24 17:44:41 +00002385 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2386 if (getLexer().isNot(AsmToken::Comma))
2387 return TokError("unexpected token in '.fill' directive");
2388 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002389
Roman Divacky9c607102013-09-24 17:44:41 +00002390 if (parseAbsoluteExpression(FillExpr))
2391 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002392
Roman Divacky9c607102013-09-24 17:44:41 +00002393 if (getLexer().isNot(AsmToken::EndOfStatement))
2394 return TokError("unexpected token in '.fill' directive");
2395
2396 Lex();
2397 }
2398 }
Daniel Dunbara0d14262009-06-24 23:30:00 +00002399
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002400 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2401 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002402
2403 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002404 getStreamer().EmitIntValue(FillExpr, FillSize);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002405
2406 return false;
2407}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002408
Jim Grosbach4a200922013-09-20 23:08:21 +00002409/// parseDirectiveOrg
Daniel Dunbarc238b582009-06-25 22:44:51 +00002410/// ::= .org expression [ , expression ]
Jim Grosbach4a200922013-09-20 23:08:21 +00002411bool AsmParser::parseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002412 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002413
Daniel Dunbar821e3332009-08-31 08:09:28 +00002414 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002415 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002416 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002417 return true;
2418
2419 // Parse optional fill expression.
2420 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002421 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2422 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002423 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002424 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002425
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002426 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002427 return true;
2428
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002429 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002430 return TokError("unexpected token in '.org' directive");
2431 }
2432
Sean Callanan79ed1a82010-01-19 20:22:31 +00002433 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002434
Jim Grosbachebd4c052012-01-27 00:37:08 +00002435 // Only limited forms of relocatable expressions are accepted here, it
2436 // has to be relative to the current section. The streamer will return
2437 // 'true' if the expression wasn't evaluatable.
2438 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2439 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002440
2441 return false;
2442}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443
Jim Grosbach4a200922013-09-20 23:08:21 +00002444/// parseDirectiveAlign
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002445/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4a200922013-09-20 23:08:21 +00002446bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002447 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002448
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002449 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002450 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002451 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002452 return true;
2453
2454 SMLoc MaxBytesLoc;
2455 bool HasFillExpr = false;
2456 int64_t FillExpr = 0;
2457 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002458 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2459 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002460 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002461 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002462
2463 // The fill expression can be omitted while specifying a maximum number of
2464 // alignment bytes, e.g:
2465 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002466 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002467 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002468 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002469 return true;
2470 }
2471
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002472 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2473 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002474 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002475 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002476
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002477 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002478 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002479 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002480
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002481 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002482 return TokError("unexpected token in directive");
2483 }
2484 }
2485
Sean Callanan79ed1a82010-01-19 20:22:31 +00002486 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002487
Daniel Dunbar648ac512010-05-17 21:54:30 +00002488 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002489 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002490
2491 // Compute alignment in bytes.
2492 if (IsPow2) {
2493 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002494 if (Alignment >= 32) {
2495 Error(AlignmentLoc, "invalid alignment value");
2496 Alignment = 31;
2497 }
2498
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002499 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002500 } else {
2501 // Reject alignments that aren't a power of two, for gas compatibility.
2502 if (!isPowerOf2_64(Alignment))
2503 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002504 }
2505
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002506 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002507 if (MaxBytesLoc.isValid()) {
2508 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002509 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4a200922013-09-20 23:08:21 +00002510 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002511 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002512 }
2513
2514 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002515 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4a200922013-09-20 23:08:21 +00002516 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002517 MaxBytesToFill = 0;
2518 }
2519 }
2520
Daniel Dunbar648ac512010-05-17 21:54:30 +00002521 // Check whether we should use optimal code alignment for this .align
2522 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002523 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002524 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2525 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002526 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002527 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002528 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002529 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2530 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002531 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002532
2533 return false;
2534}
2535
Jim Grosbach4a200922013-09-20 23:08:21 +00002536/// parseDirectiveFile
Eli Bendersky6ee13082013-01-15 22:59:42 +00002537/// ::= .file [number] filename
2538/// ::= .file number directory filename
Jim Grosbach4a200922013-09-20 23:08:21 +00002539bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002540 // FIXME: I'm not sure what this is.
2541 int64_t FileNumber = -1;
2542 SMLoc FileNumberLoc = getLexer().getLoc();
2543 if (getLexer().is(AsmToken::Integer)) {
2544 FileNumber = getTok().getIntVal();
2545 Lex();
2546
2547 if (FileNumber < 1)
2548 return TokError("file number less than one");
2549 }
2550
2551 if (getLexer().isNot(AsmToken::String))
2552 return TokError("unexpected token in '.file' directive");
2553
2554 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gaoed119822013-09-05 19:14:26 +00002555 // Allow the strings to have escaped octal character sequence.
2556 std::string Path = getTok().getString();
2557 if (parseEscapedString(Path))
2558 return true;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002559 Lex();
2560
2561 StringRef Directory;
2562 StringRef Filename;
Yunzhong Gaoed119822013-09-05 19:14:26 +00002563 std::string FilenameData;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002564 if (getLexer().is(AsmToken::String)) {
2565 if (FileNumber == -1)
2566 return TokError("explicit path specified, but no file number");
Yunzhong Gaoed119822013-09-05 19:14:26 +00002567 if (parseEscapedString(FilenameData))
2568 return true;
2569 Filename = FilenameData;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002570 Directory = Path;
2571 Lex();
2572 } else {
2573 Filename = Path;
2574 }
2575
2576 if (getLexer().isNot(AsmToken::EndOfStatement))
2577 return TokError("unexpected token in '.file' directive");
2578
2579 if (FileNumber == -1)
2580 getStreamer().EmitFileDirective(Filename);
2581 else {
2582 if (getContext().getGenDwarfForAssembly() == true)
Jim Grosbach4a200922013-09-20 23:08:21 +00002583 Error(DirectiveLoc,
2584 "input can't have .file dwarf directives when -g is "
2585 "used to generate dwarf debug info for assembly code");
Eli Bendersky6ee13082013-01-15 22:59:42 +00002586
2587 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2588 Error(FileNumberLoc, "file number already allocated");
2589 }
2590
2591 return false;
2592}
2593
Jim Grosbach4a200922013-09-20 23:08:21 +00002594/// parseDirectiveLine
Eli Bendersky6ee13082013-01-15 22:59:42 +00002595/// ::= .line [number]
Jim Grosbach4a200922013-09-20 23:08:21 +00002596bool AsmParser::parseDirectiveLine() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002597 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2598 if (getLexer().isNot(AsmToken::Integer))
2599 return TokError("unexpected token in '.line' directive");
2600
2601 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4a200922013-09-20 23:08:21 +00002602 (void)LineNumber;
Eli Bendersky6ee13082013-01-15 22:59:42 +00002603 Lex();
2604
2605 // FIXME: Do something with the .line.
2606 }
2607
2608 if (getLexer().isNot(AsmToken::EndOfStatement))
2609 return TokError("unexpected token in '.line' directive");
2610
2611 return false;
2612}
2613
Jim Grosbach4a200922013-09-20 23:08:21 +00002614/// parseDirectiveLoc
Eli Bendersky6ee13082013-01-15 22:59:42 +00002615/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2616/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2617/// The first number is a file number, must have been previously assigned with
2618/// a .file directive, the second number is the line number and optionally the
2619/// third number is a column position (zero if not specified). The remaining
2620/// optional items are .loc sub-directives.
Jim Grosbach4a200922013-09-20 23:08:21 +00002621bool AsmParser::parseDirectiveLoc() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002622 if (getLexer().isNot(AsmToken::Integer))
2623 return TokError("unexpected token in '.loc' directive");
2624 int64_t FileNumber = getTok().getIntVal();
2625 if (FileNumber < 1)
2626 return TokError("file number less than one in '.loc' directive");
2627 if (!getContext().isValidDwarfFileNumber(FileNumber))
2628 return TokError("unassigned file number in '.loc' directive");
2629 Lex();
2630
2631 int64_t LineNumber = 0;
2632 if (getLexer().is(AsmToken::Integer)) {
2633 LineNumber = getTok().getIntVal();
2634 if (LineNumber < 1)
2635 return TokError("line number less than one in '.loc' directive");
2636 Lex();
2637 }
2638
2639 int64_t ColumnPos = 0;
2640 if (getLexer().is(AsmToken::Integer)) {
2641 ColumnPos = getTok().getIntVal();
2642 if (ColumnPos < 0)
2643 return TokError("column position less than zero in '.loc' directive");
2644 Lex();
2645 }
2646
2647 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2648 unsigned Isa = 0;
2649 int64_t Discriminator = 0;
2650 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2651 for (;;) {
2652 if (getLexer().is(AsmToken::EndOfStatement))
2653 break;
2654
2655 StringRef Name;
2656 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002657 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002658 return TokError("unexpected token in '.loc' directive");
2659
2660 if (Name == "basic_block")
2661 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2662 else if (Name == "prologue_end")
2663 Flags |= DWARF2_FLAG_PROLOGUE_END;
2664 else if (Name == "epilogue_begin")
2665 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2666 else if (Name == "is_stmt") {
2667 Loc = getTok().getLoc();
2668 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002669 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002670 return true;
2671 // The expression must be the constant 0 or 1.
2672 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2673 int Value = MCE->getValue();
2674 if (Value == 0)
2675 Flags &= ~DWARF2_FLAG_IS_STMT;
2676 else if (Value == 1)
2677 Flags |= DWARF2_FLAG_IS_STMT;
2678 else
2679 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002680 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002681 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2682 }
Craig Topperefa703d2013-04-22 04:22:40 +00002683 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002684 Loc = getTok().getLoc();
2685 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002686 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002687 return true;
2688 // The expression must be a constant greater or equal to 0.
2689 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2690 int Value = MCE->getValue();
2691 if (Value < 0)
2692 return Error(Loc, "isa number less than zero");
2693 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002694 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002695 return Error(Loc, "isa number not a constant value");
2696 }
Craig Topperefa703d2013-04-22 04:22:40 +00002697 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002698 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002699 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002700 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002701 return Error(Loc, "unknown sub-directive in '.loc' directive");
2702 }
2703
2704 if (getLexer().is(AsmToken::EndOfStatement))
2705 break;
2706 }
2707 }
2708
2709 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2710 Isa, Discriminator, StringRef());
2711
2712 return false;
2713}
2714
Jim Grosbach4a200922013-09-20 23:08:21 +00002715/// parseDirectiveStabs
Eli Bendersky6ee13082013-01-15 22:59:42 +00002716/// ::= .stabs string, number, number, number
Jim Grosbach4a200922013-09-20 23:08:21 +00002717bool AsmParser::parseDirectiveStabs() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002718 return TokError("unsupported directive '.stabs'");
2719}
2720
Jim Grosbach4a200922013-09-20 23:08:21 +00002721/// parseDirectiveCFISections
Eli Bendersky6ee13082013-01-15 22:59:42 +00002722/// ::= .cfi_sections section [, section]
Jim Grosbach4a200922013-09-20 23:08:21 +00002723bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002724 StringRef Name;
2725 bool EH = false;
2726 bool Debug = false;
2727
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002728 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002729 return TokError("Expected an identifier");
2730
2731 if (Name == ".eh_frame")
2732 EH = true;
2733 else if (Name == ".debug_frame")
2734 Debug = true;
2735
2736 if (getLexer().is(AsmToken::Comma)) {
2737 Lex();
2738
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002739 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002740 return TokError("Expected an identifier");
2741
2742 if (Name == ".eh_frame")
2743 EH = true;
2744 else if (Name == ".debug_frame")
2745 Debug = true;
2746 }
2747
2748 getStreamer().EmitCFISections(EH, Debug);
2749 return false;
2750}
2751
Jim Grosbach4a200922013-09-20 23:08:21 +00002752/// parseDirectiveCFIStartProc
Eli Bendersky6ee13082013-01-15 22:59:42 +00002753/// ::= .cfi_startproc
Jim Grosbach4a200922013-09-20 23:08:21 +00002754bool AsmParser::parseDirectiveCFIStartProc() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002755 getStreamer().EmitCFIStartProc();
2756 return false;
2757}
2758
Jim Grosbach4a200922013-09-20 23:08:21 +00002759/// parseDirectiveCFIEndProc
Eli Bendersky6ee13082013-01-15 22:59:42 +00002760/// ::= .cfi_endproc
Jim Grosbach4a200922013-09-20 23:08:21 +00002761bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002762 getStreamer().EmitCFIEndProc();
2763 return false;
2764}
2765
Jim Grosbach4a200922013-09-20 23:08:21 +00002766/// \brief parse register name or number.
2767bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky6ee13082013-01-15 22:59:42 +00002768 SMLoc DirectiveLoc) {
2769 unsigned RegNo;
2770
2771 if (getLexer().isNot(AsmToken::Integer)) {
2772 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2773 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002774 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002775 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002776 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002777
2778 return false;
2779}
2780
Jim Grosbach4a200922013-09-20 23:08:21 +00002781/// parseDirectiveCFIDefCfa
Eli Bendersky6ee13082013-01-15 22:59:42 +00002782/// ::= .cfi_def_cfa register, offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002783bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002784 int64_t Register = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002785 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002786 return true;
2787
2788 if (getLexer().isNot(AsmToken::Comma))
2789 return TokError("unexpected token in directive");
2790 Lex();
2791
2792 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002793 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002794 return true;
2795
2796 getStreamer().EmitCFIDefCfa(Register, Offset);
2797 return false;
2798}
2799
Jim Grosbach4a200922013-09-20 23:08:21 +00002800/// parseDirectiveCFIDefCfaOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002801/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002802bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002803 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002804 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002805 return true;
2806
2807 getStreamer().EmitCFIDefCfaOffset(Offset);
2808 return false;
2809}
2810
Jim Grosbach4a200922013-09-20 23:08:21 +00002811/// parseDirectiveCFIRegister
Eli Bendersky6ee13082013-01-15 22:59:42 +00002812/// ::= .cfi_register register, register
Jim Grosbach4a200922013-09-20 23:08:21 +00002813bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002814 int64_t Register1 = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002815 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002816 return true;
2817
2818 if (getLexer().isNot(AsmToken::Comma))
2819 return TokError("unexpected token in directive");
2820 Lex();
2821
2822 int64_t Register2 = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002823 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002824 return true;
2825
2826 getStreamer().EmitCFIRegister(Register1, Register2);
2827 return false;
2828}
2829
Jim Grosbach4a200922013-09-20 23:08:21 +00002830/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002831/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4a200922013-09-20 23:08:21 +00002832bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002833 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002834 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002835 return true;
2836
2837 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2838 return false;
2839}
2840
Jim Grosbach4a200922013-09-20 23:08:21 +00002841/// parseDirectiveCFIDefCfaRegister
Eli Bendersky6ee13082013-01-15 22:59:42 +00002842/// ::= .cfi_def_cfa_register register
Jim Grosbach4a200922013-09-20 23:08:21 +00002843bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002844 int64_t Register = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002845 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002846 return true;
2847
2848 getStreamer().EmitCFIDefCfaRegister(Register);
2849 return false;
2850}
2851
Jim Grosbach4a200922013-09-20 23:08:21 +00002852/// parseDirectiveCFIOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002853/// ::= .cfi_offset register, offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002854bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002855 int64_t Register = 0;
2856 int64_t Offset = 0;
2857
Jim Grosbach4a200922013-09-20 23:08:21 +00002858 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002859 return true;
2860
2861 if (getLexer().isNot(AsmToken::Comma))
2862 return TokError("unexpected token in directive");
2863 Lex();
2864
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002865 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002866 return true;
2867
2868 getStreamer().EmitCFIOffset(Register, Offset);
2869 return false;
2870}
2871
Jim Grosbach4a200922013-09-20 23:08:21 +00002872/// parseDirectiveCFIRelOffset
Eli Bendersky6ee13082013-01-15 22:59:42 +00002873/// ::= .cfi_rel_offset register, offset
Jim Grosbach4a200922013-09-20 23:08:21 +00002874bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002875 int64_t Register = 0;
2876
Jim Grosbach4a200922013-09-20 23:08:21 +00002877 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002878 return true;
2879
2880 if (getLexer().isNot(AsmToken::Comma))
2881 return TokError("unexpected token in directive");
2882 Lex();
2883
2884 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002885 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002886 return true;
2887
2888 getStreamer().EmitCFIRelOffset(Register, Offset);
2889 return false;
2890}
2891
2892static bool isValidEncoding(int64_t Encoding) {
2893 if (Encoding & ~0xff)
2894 return false;
2895
2896 if (Encoding == dwarf::DW_EH_PE_omit)
2897 return true;
2898
2899 const unsigned Format = Encoding & 0xf;
2900 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2901 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2902 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2903 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2904 return false;
2905
2906 const unsigned Application = Encoding & 0x70;
2907 if (Application != dwarf::DW_EH_PE_absptr &&
2908 Application != dwarf::DW_EH_PE_pcrel)
2909 return false;
2910
2911 return true;
2912}
2913
Jim Grosbach4a200922013-09-20 23:08:21 +00002914/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky6ee13082013-01-15 22:59:42 +00002915/// IsPersonality true for cfi_personality, false for cfi_lsda
2916/// ::= .cfi_personality encoding, [symbol_name]
2917/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4a200922013-09-20 23:08:21 +00002918bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002919 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002920 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002921 return true;
2922 if (Encoding == dwarf::DW_EH_PE_omit)
2923 return false;
2924
2925 if (!isValidEncoding(Encoding))
2926 return TokError("unsupported encoding.");
2927
2928 if (getLexer().isNot(AsmToken::Comma))
2929 return TokError("unexpected token in directive");
2930 Lex();
2931
2932 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002933 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002934 return TokError("expected identifier in directive");
2935
2936 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2937
2938 if (IsPersonality)
2939 getStreamer().EmitCFIPersonality(Sym, Encoding);
2940 else
2941 getStreamer().EmitCFILsda(Sym, Encoding);
2942 return false;
2943}
2944
Jim Grosbach4a200922013-09-20 23:08:21 +00002945/// parseDirectiveCFIRememberState
Eli Bendersky6ee13082013-01-15 22:59:42 +00002946/// ::= .cfi_remember_state
Jim Grosbach4a200922013-09-20 23:08:21 +00002947bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002948 getStreamer().EmitCFIRememberState();
2949 return false;
2950}
2951
Jim Grosbach4a200922013-09-20 23:08:21 +00002952/// parseDirectiveCFIRestoreState
Eli Bendersky6ee13082013-01-15 22:59:42 +00002953/// ::= .cfi_remember_state
Jim Grosbach4a200922013-09-20 23:08:21 +00002954bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002955 getStreamer().EmitCFIRestoreState();
2956 return false;
2957}
2958
Jim Grosbach4a200922013-09-20 23:08:21 +00002959/// parseDirectiveCFISameValue
Eli Bendersky6ee13082013-01-15 22:59:42 +00002960/// ::= .cfi_same_value register
Jim Grosbach4a200922013-09-20 23:08:21 +00002961bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002962 int64_t Register = 0;
2963
Jim Grosbach4a200922013-09-20 23:08:21 +00002964 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002965 return true;
2966
2967 getStreamer().EmitCFISameValue(Register);
2968 return false;
2969}
2970
Jim Grosbach4a200922013-09-20 23:08:21 +00002971/// parseDirectiveCFIRestore
Eli Bendersky6ee13082013-01-15 22:59:42 +00002972/// ::= .cfi_restore register
Jim Grosbach4a200922013-09-20 23:08:21 +00002973bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002974 int64_t Register = 0;
Jim Grosbach4a200922013-09-20 23:08:21 +00002975 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002976 return true;
2977
2978 getStreamer().EmitCFIRestore(Register);
2979 return false;
2980}
2981
Jim Grosbach4a200922013-09-20 23:08:21 +00002982/// parseDirectiveCFIEscape
Eli Bendersky6ee13082013-01-15 22:59:42 +00002983/// ::= .cfi_escape expression[,...]
Jim Grosbach4a200922013-09-20 23:08:21 +00002984bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002985 std::string Values;
2986 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002987 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002988 return true;
2989
2990 Values.push_back((uint8_t)CurrValue);
2991
2992 while (getLexer().is(AsmToken::Comma)) {
2993 Lex();
2994
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002995 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002996 return true;
2997
2998 Values.push_back((uint8_t)CurrValue);
2999 }
3000
3001 getStreamer().EmitCFIEscape(Values);
3002 return false;
3003}
3004
Jim Grosbach4a200922013-09-20 23:08:21 +00003005/// parseDirectiveCFISignalFrame
Eli Bendersky6ee13082013-01-15 22:59:42 +00003006/// ::= .cfi_signal_frame
Jim Grosbach4a200922013-09-20 23:08:21 +00003007bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003008 if (getLexer().isNot(AsmToken::EndOfStatement))
3009 return Error(getLexer().getLoc(),
3010 "unexpected token in '.cfi_signal_frame'");
3011
3012 getStreamer().EmitCFISignalFrame();
3013 return false;
3014}
3015
Jim Grosbach4a200922013-09-20 23:08:21 +00003016/// parseDirectiveCFIUndefined
Eli Bendersky6ee13082013-01-15 22:59:42 +00003017/// ::= .cfi_undefined register
Jim Grosbach4a200922013-09-20 23:08:21 +00003018bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003019 int64_t Register = 0;
3020
Jim Grosbach4a200922013-09-20 23:08:21 +00003021 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003022 return true;
3023
3024 getStreamer().EmitCFIUndefined(Register);
3025 return false;
3026}
3027
Jim Grosbach4a200922013-09-20 23:08:21 +00003028/// parseDirectiveMacrosOnOff
Eli Bendersky6ee13082013-01-15 22:59:42 +00003029/// ::= .macros_on
3030/// ::= .macros_off
Jim Grosbach4a200922013-09-20 23:08:21 +00003031bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003032 if (getLexer().isNot(AsmToken::EndOfStatement))
3033 return Error(getLexer().getLoc(),
3034 "unexpected token in '" + Directive + "' directive");
3035
Jim Grosbach4a200922013-09-20 23:08:21 +00003036 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky6ee13082013-01-15 22:59:42 +00003037 return false;
3038}
3039
Jim Grosbach4a200922013-09-20 23:08:21 +00003040/// parseDirectiveMacro
Eli Bendersky6ee13082013-01-15 22:59:42 +00003041/// ::= .macro name [parameters]
Jim Grosbach4a200922013-09-20 23:08:21 +00003042bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003043 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003044 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003045 return TokError("expected identifier in '.macro' directive");
3046
3047 MCAsmMacroParameters Parameters;
3048 // Argument delimiter is initially unknown. It will be set by
Jim Grosbach4a200922013-09-20 23:08:21 +00003049 // parseMacroArgument()
Eli Bendersky6ee13082013-01-15 22:59:42 +00003050 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3051 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3052 for (;;) {
3053 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003054 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003055 return TokError("expected identifier in '.macro' directive");
3056
3057 if (getLexer().is(AsmToken::Equal)) {
3058 Lex();
Jim Grosbach4a200922013-09-20 23:08:21 +00003059 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003060 return true;
3061 }
3062
3063 Parameters.push_back(Parameter);
3064
3065 if (getLexer().is(AsmToken::Comma))
3066 Lex();
3067 else if (getLexer().is(AsmToken::EndOfStatement))
3068 break;
3069 }
3070 }
3071
3072 // Eat the end of statement.
3073 Lex();
3074
3075 AsmToken EndToken, StartToken = getTok();
3076
3077 // Lex the macro definition.
3078 for (;;) {
3079 // Check whether we have reached the end of the file.
3080 if (getLexer().is(AsmToken::Eof))
3081 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3082
3083 // Otherwise, check whether we have reach the .endmacro.
3084 if (getLexer().is(AsmToken::Identifier) &&
3085 (getTok().getIdentifier() == ".endm" ||
3086 getTok().getIdentifier() == ".endmacro")) {
3087 EndToken = getTok();
3088 Lex();
3089 if (getLexer().isNot(AsmToken::EndOfStatement))
3090 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3091 "' directive");
3092 break;
3093 }
3094
3095 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003096 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003097 }
3098
Jim Grosbach4a200922013-09-20 23:08:21 +00003099 if (lookupMacro(Name)) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003100 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3101 }
3102
3103 const char *BodyStart = StartToken.getLoc().getPointer();
3104 const char *BodyEnd = EndToken.getLoc().getPointer();
3105 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4a200922013-09-20 23:08:21 +00003106 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3107 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
Eli Bendersky6ee13082013-01-15 22:59:42 +00003108 return false;
3109}
3110
Jim Grosbach4a200922013-09-20 23:08:21 +00003111/// checkForBadMacro
Kevin Enderby221514e2013-01-22 21:44:53 +00003112///
3113/// With the support added for named parameters there may be code out there that
3114/// is transitioning from positional parameters. In versions of gas that did
3115/// not support named parameters they would be ignored on the macro defintion.
3116/// But to support both styles of parameters this is not possible so if a macro
3117/// defintion has named parameters but does not use them and has what appears
3118/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3119/// warning that the positional parameter found in body which have no effect.
3120/// Hoping the developer will either remove the named parameters from the macro
3121/// definiton so the positional parameters get used if that was what was
3122/// intended or change the macro to use the named parameters. It is possible
3123/// this warning will trigger when the none of the named parameters are used
3124/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4a200922013-09-20 23:08:21 +00003125void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby221514e2013-01-22 21:44:53 +00003126 StringRef Body,
3127 MCAsmMacroParameters Parameters) {
3128 // If this macro is not defined with named parameters the warning we are
3129 // checking for here doesn't apply.
3130 unsigned NParameters = Parameters.size();
3131 if (NParameters == 0)
3132 return;
3133
3134 bool NamedParametersFound = false;
3135 bool PositionalParametersFound = false;
3136
3137 // Look at the body of the macro for use of both the named parameters and what
3138 // are likely to be positional parameters. This is what expandMacro() is
3139 // doing when it finds the parameters in the body.
3140 while (!Body.empty()) {
3141 // Scan for the next possible parameter.
3142 std::size_t End = Body.size(), Pos = 0;
3143 for (; Pos != End; ++Pos) {
3144 // Check for a substitution or escape.
3145 // This macro is defined with parameters, look for \foo, \bar, etc.
3146 if (Body[Pos] == '\\' && Pos + 1 != End)
3147 break;
3148
3149 // This macro should have parameters, but look for $0, $1, ..., $n too.
3150 if (Body[Pos] != '$' || Pos + 1 == End)
3151 continue;
3152 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003153 if (Next == '$' || Next == 'n' ||
3154 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003155 break;
3156 }
3157
3158 // Check if we reached the end.
3159 if (Pos == End)
3160 break;
3161
3162 if (Body[Pos] == '$') {
Jim Grosbach4a200922013-09-20 23:08:21 +00003163 switch (Body[Pos + 1]) {
3164 // $$ => $
Kevin Enderby221514e2013-01-22 21:44:53 +00003165 case '$':
3166 break;
3167
Jim Grosbach4a200922013-09-20 23:08:21 +00003168 // $n => number of arguments
Kevin Enderby221514e2013-01-22 21:44:53 +00003169 case 'n':
3170 PositionalParametersFound = true;
3171 break;
3172
Jim Grosbach4a200922013-09-20 23:08:21 +00003173 // $[0-9] => argument
Kevin Enderby221514e2013-01-22 21:44:53 +00003174 default: {
3175 PositionalParametersFound = true;
3176 break;
Jim Grosbach4a200922013-09-20 23:08:21 +00003177 }
Kevin Enderby221514e2013-01-22 21:44:53 +00003178 }
3179 Pos += 2;
3180 } else {
3181 unsigned I = Pos + 1;
3182 while (isIdentifierChar(Body[I]) && I + 1 != End)
3183 ++I;
3184
Jim Grosbach4a200922013-09-20 23:08:21 +00003185 const char *Begin = Body.data() + Pos + 1;
3186 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby221514e2013-01-22 21:44:53 +00003187 unsigned Index = 0;
3188 for (; Index < NParameters; ++Index)
3189 if (Parameters[Index].first == Argument)
3190 break;
3191
3192 if (Index == NParameters) {
Jim Grosbach4a200922013-09-20 23:08:21 +00003193 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3194 Pos += 3;
3195 else {
3196 Pos = I;
3197 }
Kevin Enderby221514e2013-01-22 21:44:53 +00003198 } else {
3199 NamedParametersFound = true;
3200 Pos += 1 + Argument.size();
3201 }
3202 }
3203 // Update the scan point.
3204 Body = Body.substr(Pos);
3205 }
3206
3207 if (!NamedParametersFound && PositionalParametersFound)
3208 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3209 "used in macro body, possible positional parameter "
3210 "found in body which will have no effect");
3211}
3212
Jim Grosbach4a200922013-09-20 23:08:21 +00003213/// parseDirectiveEndMacro
Eli Bendersky6ee13082013-01-15 22:59:42 +00003214/// ::= .endm
3215/// ::= .endmacro
Jim Grosbach4a200922013-09-20 23:08:21 +00003216bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003217 if (getLexer().isNot(AsmToken::EndOfStatement))
3218 return TokError("unexpected token in '" + Directive + "' directive");
3219
3220 // If we are inside a macro instantiation, terminate the current
3221 // instantiation.
Jim Grosbach4a200922013-09-20 23:08:21 +00003222 if (isInsideMacroInstantiation()) {
3223 handleMacroExit();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003224 return false;
3225 }
3226
3227 // Otherwise, this .endmacro is a stray entry in the file; well formed
3228 // .endmacro directives are handled during the macro definition parsing.
3229 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4a200922013-09-20 23:08:21 +00003230 "no current macro definition");
Eli Bendersky6ee13082013-01-15 22:59:42 +00003231}
3232
Jim Grosbach4a200922013-09-20 23:08:21 +00003233/// parseDirectivePurgeMacro
Eli Bendersky6ee13082013-01-15 22:59:42 +00003234/// ::= .purgem
Jim Grosbach4a200922013-09-20 23:08:21 +00003235bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky6ee13082013-01-15 22:59:42 +00003236 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003237 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003238 return TokError("expected identifier in '.purgem' directive");
3239
3240 if (getLexer().isNot(AsmToken::EndOfStatement))
3241 return TokError("unexpected token in '.purgem' directive");
3242
Jim Grosbach4a200922013-09-20 23:08:21 +00003243 if (!lookupMacro(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003244 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3245
Jim Grosbach4a200922013-09-20 23:08:21 +00003246 undefineMacro(Name);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003247 return false;
3248}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003249
Jim Grosbach4a200922013-09-20 23:08:21 +00003250/// parseDirectiveBundleAlignMode
Eli Bendersky4766ef42012-12-20 19:05:53 +00003251/// ::= {.bundle_align_mode} expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003252bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003253 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003254
3255 // Expect a single argument: an expression that evaluates to a constant
3256 // in the inclusive range 0-30.
3257 SMLoc ExprLoc = getLexer().getLoc();
3258 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003259 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003260 return true;
3261 else if (getLexer().isNot(AsmToken::EndOfStatement))
3262 return TokError("unexpected token after expression in"
3263 " '.bundle_align_mode' directive");
3264 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3265 return Error(ExprLoc,
3266 "invalid bundle alignment size (expected between 0 and 30)");
3267
3268 Lex();
3269
3270 // Because of AlignSizePow2's verified range we can safely truncate it to
3271 // unsigned.
3272 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3273 return false;
3274}
3275
Jim Grosbach4a200922013-09-20 23:08:21 +00003276/// parseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003277/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4a200922013-09-20 23:08:21 +00003278bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003279 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003280 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003281
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003282 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3283 StringRef Option;
3284 SMLoc Loc = getTok().getLoc();
3285 const char *kInvalidOptionError =
Jim Grosbach4a200922013-09-20 23:08:21 +00003286 "invalid option for '.bundle_lock' directive";
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003287
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003288 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003289 return Error(Loc, kInvalidOptionError);
3290
3291 if (Option != "align_to_end")
3292 return Error(Loc, kInvalidOptionError);
3293 else if (getLexer().isNot(AsmToken::EndOfStatement))
3294 return Error(Loc,
3295 "unexpected token after '.bundle_lock' directive option");
3296 AlignToEnd = true;
3297 }
3298
Eli Bendersky4766ef42012-12-20 19:05:53 +00003299 Lex();
3300
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003301 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003302 return false;
3303}
3304
Jim Grosbach4a200922013-09-20 23:08:21 +00003305/// parseDirectiveBundleLock
Eli Bendersky4766ef42012-12-20 19:05:53 +00003306/// ::= {.bundle_lock}
Jim Grosbach4a200922013-09-20 23:08:21 +00003307bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003308 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003309
3310 if (getLexer().isNot(AsmToken::EndOfStatement))
3311 return TokError("unexpected token in '.bundle_unlock' directive");
3312 Lex();
3313
3314 getStreamer().EmitBundleUnlock();
3315 return false;
3316}
3317
Jim Grosbach4a200922013-09-20 23:08:21 +00003318/// parseDirectiveSpace
Eli Bendersky6ee13082013-01-15 22:59:42 +00003319/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4a200922013-09-20 23:08:21 +00003320bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003321 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003322
3323 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003324 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003325 return true;
3326
3327 int64_t FillExpr = 0;
3328 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3329 if (getLexer().isNot(AsmToken::Comma))
3330 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3331 Lex();
3332
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003333 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003334 return true;
3335
3336 if (getLexer().isNot(AsmToken::EndOfStatement))
3337 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3338 }
3339
3340 Lex();
3341
3342 if (NumBytes <= 0)
Jim Grosbach4a200922013-09-20 23:08:21 +00003343 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3344 "' directive");
Eli Bendersky6ee13082013-01-15 22:59:42 +00003345
3346 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00003347 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003348
3349 return false;
3350}
3351
Jim Grosbach4a200922013-09-20 23:08:21 +00003352/// parseDirectiveLEB128
Eli Bendersky6ee13082013-01-15 22:59:42 +00003353/// ::= (.sleb128 | .uleb128) expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003354bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003355 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003356 const MCExpr *Value;
3357
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003358 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003359 return true;
3360
3361 if (getLexer().isNot(AsmToken::EndOfStatement))
3362 return TokError("unexpected token in directive");
3363
3364 if (Signed)
3365 getStreamer().EmitSLEB128Value(Value);
3366 else
3367 getStreamer().EmitULEB128Value(Value);
3368
3369 return false;
3370}
3371
Jim Grosbach4a200922013-09-20 23:08:21 +00003372/// parseDirectiveSymbolAttribute
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003373/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4a200922013-09-20 23:08:21 +00003374bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003375 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003376 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003377 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003378 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003379
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003380 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003381 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003382
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003383 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003384
Jim Grosbach10ec6502011-09-15 17:56:49 +00003385 // Assembler local symbols don't make any sense here. Complain loudly.
3386 if (Sym->isTemporary())
3387 return Error(Loc, "non-local symbol required in directive");
3388
Saleem Abdulrasool1c9cd022013-08-09 01:52:03 +00003389 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3390 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003391
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003392 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003393 break;
3394
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003395 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003396 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003397 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003398 }
3399 }
3400
Sean Callanan79ed1a82010-01-19 20:22:31 +00003401 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003402 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003403}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003404
Jim Grosbach4a200922013-09-20 23:08:21 +00003405/// parseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003406/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4a200922013-09-20 23:08:21 +00003407bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003408 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003409
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003410 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003411 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003412 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003413 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003414
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003415 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003416 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003417
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003418 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003419 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003420 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003421
3422 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003423 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003424 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003425 return true;
3426
3427 int64_t Pow2Alignment = 0;
3428 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003429 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003430 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003431 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003432 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003433 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003434
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003435 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3436 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003437 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3438
Chris Lattner258281d2010-01-19 06:22:22 +00003439 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003440 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3441 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003442 if (!isPowerOf2_64(Pow2Alignment))
3443 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3444 Pow2Alignment = Log2_64(Pow2Alignment);
3445 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003446 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003447
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003448 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003449 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003450
Sean Callanan79ed1a82010-01-19 20:22:31 +00003451 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003452
Chris Lattner1fc3d752009-07-09 17:25:12 +00003453 // NOTE: a size of zero for a .comm should create a undefined symbol
3454 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003455 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003456 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4a200922013-09-20 23:08:21 +00003457 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003458
Eric Christopherc260a3e2010-05-14 01:38:54 +00003459 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003460 // may internally end up wanting an alignment in bytes.
3461 // FIXME: Diagnose overflow.
3462 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003463 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4a200922013-09-20 23:08:21 +00003464 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003465
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003466 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003467 return Error(IDLoc, "invalid symbol redefinition");
3468
Chris Lattner1fc3d752009-07-09 17:25:12 +00003469 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003470 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003471 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003472 return false;
3473 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003474
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003475 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003476 return false;
3477}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003478
Jim Grosbach4a200922013-09-20 23:08:21 +00003479/// parseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003480/// ::= .abort [... message ...]
Jim Grosbach4a200922013-09-20 23:08:21 +00003481bool AsmParser::parseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003482 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003483 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003484
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003485 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003486 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003487 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003488
Sean Callanan79ed1a82010-01-19 20:22:31 +00003489 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003490
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003491 if (Str.empty())
3492 Error(Loc, ".abort detected. Assembly stopping.");
3493 else
3494 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003495 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003496
3497 return false;
3498}
Kevin Enderby71148242009-07-14 21:35:03 +00003499
Jim Grosbach4a200922013-09-20 23:08:21 +00003500/// parseDirectiveInclude
Kevin Enderby1f049b22009-07-14 23:21:55 +00003501/// ::= .include "filename"
Jim Grosbach4a200922013-09-20 23:08:21 +00003502bool AsmParser::parseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003503 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003504 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003505
Yunzhong Gaoed119822013-09-05 19:14:26 +00003506 // Allow the strings to have escaped octal character sequence.
3507 std::string Filename;
3508 if (parseEscapedString(Filename))
3509 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003510 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003511 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003512
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003513 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003514 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003515
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003516 // Attempt to switch the lexer to the included file before consuming the end
3517 // of statement to avoid losing it when we switch.
Jim Grosbach4a200922013-09-20 23:08:21 +00003518 if (enterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003519 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003520 return true;
3521 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003522
3523 return false;
3524}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003525
Jim Grosbach4a200922013-09-20 23:08:21 +00003526/// parseDirectiveIncbin
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003527/// ::= .incbin "filename"
Jim Grosbach4a200922013-09-20 23:08:21 +00003528bool AsmParser::parseDirectiveIncbin() {
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003529 if (getLexer().isNot(AsmToken::String))
3530 return TokError("expected string in '.incbin' directive");
3531
Yunzhong Gaoed119822013-09-05 19:14:26 +00003532 // Allow the strings to have escaped octal character sequence.
3533 std::string Filename;
3534 if (parseEscapedString(Filename))
3535 return true;
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003536 SMLoc IncbinLoc = getLexer().getLoc();
3537 Lex();
3538
3539 if (getLexer().isNot(AsmToken::EndOfStatement))
3540 return TokError("unexpected token in '.incbin' directive");
3541
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003542 // Attempt to process the included file.
Jim Grosbach4a200922013-09-20 23:08:21 +00003543 if (processIncbinFile(Filename)) {
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003544 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3545 return true;
3546 }
3547
3548 return false;
3549}
3550
Jim Grosbach4a200922013-09-20 23:08:21 +00003551/// parseDirectiveIf
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003552/// ::= .if expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003553bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003554 TheCondStack.push_back(TheCondState);
3555 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003556 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003557 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003558 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003559 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003560 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003561 return true;
3562
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003563 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003564 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003565
Sean Callanan79ed1a82010-01-19 20:22:31 +00003566 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003567
3568 TheCondState.CondMet = ExprValue;
3569 TheCondState.Ignore = !TheCondState.CondMet;
3570 }
3571
3572 return false;
3573}
3574
Jim Grosbach4a200922013-09-20 23:08:21 +00003575/// parseDirectiveIfb
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003576/// ::= .ifb string
Jim Grosbach4a200922013-09-20 23:08:21 +00003577bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003578 TheCondStack.push_back(TheCondState);
3579 TheCondState.TheCond = AsmCond::IfCond;
3580
Benjamin Kramer29739e72012-05-12 16:52:21 +00003581 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003582 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003583 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003584 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003585
3586 if (getLexer().isNot(AsmToken::EndOfStatement))
3587 return TokError("unexpected token in '.ifb' directive");
3588
3589 Lex();
3590
3591 TheCondState.CondMet = ExpectBlank == Str.empty();
3592 TheCondState.Ignore = !TheCondState.CondMet;
3593 }
3594
3595 return false;
3596}
3597
Jim Grosbach4a200922013-09-20 23:08:21 +00003598/// parseDirectiveIfc
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003599/// ::= .ifc string1, string2
Jim Grosbach4a200922013-09-20 23:08:21 +00003600bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003601 TheCondStack.push_back(TheCondState);
3602 TheCondState.TheCond = AsmCond::IfCond;
3603
Benjamin Kramer29739e72012-05-12 16:52:21 +00003604 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003605 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003606 } else {
Jim Grosbach4a200922013-09-20 23:08:21 +00003607 StringRef Str1 = parseStringToComma();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003608
3609 if (getLexer().isNot(AsmToken::Comma))
3610 return TokError("unexpected token in '.ifc' directive");
3611
3612 Lex();
3613
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003614 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003615
3616 if (getLexer().isNot(AsmToken::EndOfStatement))
3617 return TokError("unexpected token in '.ifc' directive");
3618
3619 Lex();
3620
3621 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3622 TheCondState.Ignore = !TheCondState.CondMet;
3623 }
3624
3625 return false;
3626}
3627
Jim Grosbach4a200922013-09-20 23:08:21 +00003628/// parseDirectiveIfdef
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003629/// ::= .ifdef symbol
Jim Grosbach4a200922013-09-20 23:08:21 +00003630bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003631 StringRef Name;
3632 TheCondStack.push_back(TheCondState);
3633 TheCondState.TheCond = AsmCond::IfCond;
3634
3635 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003636 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003637 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003638 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003639 return TokError("expected identifier after '.ifdef'");
3640
3641 Lex();
3642
3643 MCSymbol *Sym = getContext().LookupSymbol(Name);
3644
3645 if (expect_defined)
3646 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3647 else
3648 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3649 TheCondState.Ignore = !TheCondState.CondMet;
3650 }
3651
3652 return false;
3653}
3654
Jim Grosbach4a200922013-09-20 23:08:21 +00003655/// parseDirectiveElseIf
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003656/// ::= .elseif expression
Jim Grosbach4a200922013-09-20 23:08:21 +00003657bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003658 if (TheCondState.TheCond != AsmCond::IfCond &&
3659 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003660 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3661 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003662 TheCondState.TheCond = AsmCond::ElseIfCond;
3663
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003664 bool LastIgnoreState = false;
3665 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003666 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003667 if (LastIgnoreState || TheCondState.CondMet) {
3668 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003669 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003670 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003671 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003672 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003673 return true;
3674
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003675 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003676 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003677
Sean Callanan79ed1a82010-01-19 20:22:31 +00003678 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003679 TheCondState.CondMet = ExprValue;
3680 TheCondState.Ignore = !TheCondState.CondMet;
3681 }
3682
3683 return false;
3684}
3685
Jim Grosbach4a200922013-09-20 23:08:21 +00003686/// parseDirectiveElse
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003687/// ::= .else
Jim Grosbach4a200922013-09-20 23:08:21 +00003688bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003689 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003690 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003691
Sean Callanan79ed1a82010-01-19 20:22:31 +00003692 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003693
3694 if (TheCondState.TheCond != AsmCond::IfCond &&
3695 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003696 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3697 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003698 TheCondState.TheCond = AsmCond::ElseCond;
3699 bool LastIgnoreState = false;
3700 if (!TheCondStack.empty())
3701 LastIgnoreState = TheCondStack.back().Ignore;
3702 if (LastIgnoreState || TheCondState.CondMet)
3703 TheCondState.Ignore = true;
3704 else
3705 TheCondState.Ignore = false;
3706
3707 return false;
3708}
3709
Jim Grosbach4a200922013-09-20 23:08:21 +00003710/// parseDirectiveEndIf
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003711/// ::= .endif
Jim Grosbach4a200922013-09-20 23:08:21 +00003712bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003713 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003714 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003715
Sean Callanan79ed1a82010-01-19 20:22:31 +00003716 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003717
Jim Grosbach4a200922013-09-20 23:08:21 +00003718 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003719 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3720 ".else");
3721 if (!TheCondStack.empty()) {
3722 TheCondState = TheCondStack.back();
3723 TheCondStack.pop_back();
3724 }
3725
3726 return false;
3727}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003728
Eli Bendersky6ee13082013-01-15 22:59:42 +00003729void AsmParser::initializeDirectiveKindMap() {
3730 DirectiveKindMap[".set"] = DK_SET;
3731 DirectiveKindMap[".equ"] = DK_EQU;
3732 DirectiveKindMap[".equiv"] = DK_EQUIV;
3733 DirectiveKindMap[".ascii"] = DK_ASCII;
3734 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3735 DirectiveKindMap[".string"] = DK_STRING;
3736 DirectiveKindMap[".byte"] = DK_BYTE;
3737 DirectiveKindMap[".short"] = DK_SHORT;
3738 DirectiveKindMap[".value"] = DK_VALUE;
3739 DirectiveKindMap[".2byte"] = DK_2BYTE;
3740 DirectiveKindMap[".long"] = DK_LONG;
3741 DirectiveKindMap[".int"] = DK_INT;
3742 DirectiveKindMap[".4byte"] = DK_4BYTE;
3743 DirectiveKindMap[".quad"] = DK_QUAD;
3744 DirectiveKindMap[".8byte"] = DK_8BYTE;
3745 DirectiveKindMap[".single"] = DK_SINGLE;
3746 DirectiveKindMap[".float"] = DK_FLOAT;
3747 DirectiveKindMap[".double"] = DK_DOUBLE;
3748 DirectiveKindMap[".align"] = DK_ALIGN;
3749 DirectiveKindMap[".align32"] = DK_ALIGN32;
3750 DirectiveKindMap[".balign"] = DK_BALIGN;
3751 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3752 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3753 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3754 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3755 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3756 DirectiveKindMap[".org"] = DK_ORG;
3757 DirectiveKindMap[".fill"] = DK_FILL;
3758 DirectiveKindMap[".zero"] = DK_ZERO;
3759 DirectiveKindMap[".extern"] = DK_EXTERN;
3760 DirectiveKindMap[".globl"] = DK_GLOBL;
3761 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky6ee13082013-01-15 22:59:42 +00003762 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3763 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3764 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3765 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3766 DirectiveKindMap[".reference"] = DK_REFERENCE;
3767 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3768 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3769 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3770 DirectiveKindMap[".comm"] = DK_COMM;
3771 DirectiveKindMap[".common"] = DK_COMMON;
3772 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3773 DirectiveKindMap[".abort"] = DK_ABORT;
3774 DirectiveKindMap[".include"] = DK_INCLUDE;
3775 DirectiveKindMap[".incbin"] = DK_INCBIN;
3776 DirectiveKindMap[".code16"] = DK_CODE16;
3777 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3778 DirectiveKindMap[".rept"] = DK_REPT;
3779 DirectiveKindMap[".irp"] = DK_IRP;
3780 DirectiveKindMap[".irpc"] = DK_IRPC;
3781 DirectiveKindMap[".endr"] = DK_ENDR;
3782 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3783 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3784 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3785 DirectiveKindMap[".if"] = DK_IF;
3786 DirectiveKindMap[".ifb"] = DK_IFB;
3787 DirectiveKindMap[".ifnb"] = DK_IFNB;
3788 DirectiveKindMap[".ifc"] = DK_IFC;
3789 DirectiveKindMap[".ifnc"] = DK_IFNC;
3790 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3791 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3792 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3793 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3794 DirectiveKindMap[".else"] = DK_ELSE;
3795 DirectiveKindMap[".endif"] = DK_ENDIF;
3796 DirectiveKindMap[".skip"] = DK_SKIP;
3797 DirectiveKindMap[".space"] = DK_SPACE;
3798 DirectiveKindMap[".file"] = DK_FILE;
3799 DirectiveKindMap[".line"] = DK_LINE;
3800 DirectiveKindMap[".loc"] = DK_LOC;
3801 DirectiveKindMap[".stabs"] = DK_STABS;
3802 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3803 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3804 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3805 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3806 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3807 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3808 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3809 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3810 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3811 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3812 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3813 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3814 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3815 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3816 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3817 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3818 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3819 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3820 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3821 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3822 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3823 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3824 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3825 DirectiveKindMap[".macro"] = DK_MACRO;
3826 DirectiveKindMap[".endm"] = DK_ENDM;
3827 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3828 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003829}
3830
Jim Grosbach4a200922013-09-20 23:08:21 +00003831MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003832 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003833
Rafael Espindola761cb062012-06-03 23:57:14 +00003834 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003835 for (;;) {
3836 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003837 if (getLexer().is(AsmToken::Eof)) {
3838 Error(DirectiveLoc, "no matching '.endr' in definition");
3839 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003840 }
3841
Rafael Espindola761cb062012-06-03 23:57:14 +00003842 if (Lexer.is(AsmToken::Identifier) &&
3843 (getTok().getIdentifier() == ".rept")) {
3844 ++NestLevel;
3845 }
3846
3847 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4a200922013-09-20 23:08:21 +00003848 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola761cb062012-06-03 23:57:14 +00003849 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003850 EndToken = getTok();
3851 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003852 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3853 TokError("unexpected token in '.endr' directive");
3854 return 0;
3855 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003856 break;
3857 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003858 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003859 }
3860
Rafael Espindola761cb062012-06-03 23:57:14 +00003861 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003862 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003863 }
3864
3865 const char *BodyStart = StartToken.getLoc().getPointer();
3866 const char *BodyEnd = EndToken.getLoc().getPointer();
3867 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3868
Rafael Espindola761cb062012-06-03 23:57:14 +00003869 // We Are Anonymous.
3870 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003871 MCAsmMacroParameters Parameters;
Benjamin Kramera2b0c332013-08-04 09:06:29 +00003872 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3873 return &MacroLikeBodies.back();
Rafael Espindola761cb062012-06-03 23:57:14 +00003874}
3875
Jim Grosbach4a200922013-09-20 23:08:21 +00003876void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003877 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003878 OS << ".endr\n";
3879
3880 MemoryBuffer *Instantiation =
Jim Grosbach4a200922013-09-20 23:08:21 +00003881 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003882
Rafael Espindola761cb062012-06-03 23:57:14 +00003883 // Create the macro instantiation object and add to the current macro
3884 // instantiation stack.
Jim Grosbach4a200922013-09-20 23:08:21 +00003885 MacroInstantiation *MI = new MacroInstantiation(
3886 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
Rafael Espindola761cb062012-06-03 23:57:14 +00003887 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003888
Rafael Espindola761cb062012-06-03 23:57:14 +00003889 // Jump to the macro instantiation and prime the lexer.
3890 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3891 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3892 Lex();
3893}
3894
Jim Grosbach4a200922013-09-20 23:08:21 +00003895bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc) {
Rafael Espindola761cb062012-06-03 23:57:14 +00003896 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003897 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003898 return TokError("unexpected token in '.rept' directive");
3899
3900 if (Count < 0)
3901 return TokError("Count is negative");
3902
3903 if (Lexer.isNot(AsmToken::EndOfStatement))
3904 return TokError("unexpected token in '.rept' directive");
3905
3906 // Eat the end of statement.
3907 Lex();
3908
3909 // Lex the rept definition.
Jim Grosbach4a200922013-09-20 23:08:21 +00003910 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003911 if (!M)
3912 return true;
3913
3914 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3915 // to hold the macro body with substitutions.
3916 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003917 MCAsmMacroParameters Parameters;
3918 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003919 raw_svector_ostream OS(Buf);
3920 while (Count--) {
3921 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3922 return true;
3923 }
Jim Grosbach4a200922013-09-20 23:08:21 +00003924 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003925
3926 return false;
3927}
3928
Jim Grosbach4a200922013-09-20 23:08:21 +00003929/// parseDirectiveIrp
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003930/// ::= .irp symbol,values
Jim Grosbach4a200922013-09-20 23:08:21 +00003931bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003932 MCAsmMacroParameters Parameters;
3933 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003934
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003935 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003936 return TokError("expected identifier in '.irp' directive");
3937
3938 Parameters.push_back(Parameter);
3939
3940 if (Lexer.isNot(AsmToken::Comma))
3941 return TokError("expected comma in '.irp' directive");
3942
3943 Lex();
3944
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003945 MCAsmMacroArguments A;
Jim Grosbach4a200922013-09-20 23:08:21 +00003946 if (parseMacroArguments(0, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003947 return true;
3948
3949 // Eat the end of statement.
3950 Lex();
3951
3952 // Lex the irp definition.
Jim Grosbach4a200922013-09-20 23:08:21 +00003953 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003954 if (!M)
3955 return true;
3956
3957 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3958 // to hold the macro body with substitutions.
3959 SmallString<256> Buf;
3960 raw_svector_ostream OS(Buf);
3961
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003962 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3963 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003964 Args.push_back(*i);
3965
3966 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3967 return true;
3968 }
3969
Jim Grosbach4a200922013-09-20 23:08:21 +00003970 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003971
3972 return false;
3973}
3974
Jim Grosbach4a200922013-09-20 23:08:21 +00003975/// parseDirectiveIrpc
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003976/// ::= .irpc symbol,values
Jim Grosbach4a200922013-09-20 23:08:21 +00003977bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003978 MCAsmMacroParameters Parameters;
3979 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003980
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003981 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003982 return TokError("expected identifier in '.irpc' directive");
3983
3984 Parameters.push_back(Parameter);
3985
3986 if (Lexer.isNot(AsmToken::Comma))
3987 return TokError("expected comma in '.irpc' directive");
3988
3989 Lex();
3990
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003991 MCAsmMacroArguments A;
Jim Grosbach4a200922013-09-20 23:08:21 +00003992 if (parseMacroArguments(0, A))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003993 return true;
3994
3995 if (A.size() != 1 || A.front().size() != 1)
3996 return TokError("unexpected token in '.irpc' directive");
3997
3998 // Eat the end of statement.
3999 Lex();
4000
4001 // Lex the irpc definition.
Jim Grosbach4a200922013-09-20 23:08:21 +00004002 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004003 if (!M)
4004 return true;
4005
4006 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4007 // to hold the macro body with substitutions.
4008 SmallString<256> Buf;
4009 raw_svector_ostream OS(Buf);
4010
4011 StringRef Values = A.front().front().getString();
4012 std::size_t I, End = Values.size();
4013 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00004014 MCAsmMacroArgument Arg;
Jim Grosbach4a200922013-09-20 23:08:21 +00004015 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004016
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004017 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004018 Args.push_back(Arg);
4019
4020 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4021 return true;
4022 }
4023
Jim Grosbach4a200922013-09-20 23:08:21 +00004024 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004025
4026 return false;
4027}
4028
Jim Grosbach4a200922013-09-20 23:08:21 +00004029bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola761cb062012-06-03 23:57:14 +00004030 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004031 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004032
4033 // The only .repl that should get here are the ones created by
Jim Grosbach4a200922013-09-20 23:08:21 +00004034 // instantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004035 assert(getLexer().is(AsmToken::EndOfStatement));
4036
Jim Grosbach4a200922013-09-20 23:08:21 +00004037 handleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004038 return false;
4039}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004040
Jim Grosbach4a200922013-09-20 23:08:21 +00004041bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer75234372013-02-15 20:37:21 +00004042 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004043 const MCExpr *Value;
4044 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004045 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004046 return true;
4047 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4048 if (!MCE)
4049 return Error(ExprLoc, "unexpected expression in _emit");
4050 uint64_t IntValue = MCE->getValue();
4051 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4052 return Error(ExprLoc, "literal value out of range for directive");
4053
Chad Rosier469b1442013-02-12 21:33:51 +00004054 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4055 return false;
4056}
4057
Jim Grosbach4a200922013-09-20 23:08:21 +00004058bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosier469b1442013-02-12 21:33:51 +00004059 const MCExpr *Value;
4060 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004061 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004062 return true;
4063 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4064 if (!MCE)
4065 return Error(ExprLoc, "unexpected expression in align");
4066 uint64_t IntValue = MCE->getValue();
4067 if (!isPowerOf2_64(IntValue))
4068 return Error(ExprLoc, "literal value not a power of two greater then zero");
4069
Jim Grosbach4a200922013-09-20 23:08:21 +00004070 Info.AsmRewrites->push_back(
4071 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004072 return false;
4073}
4074
Chad Rosier19aa3e32013-02-13 21:27:17 +00004075// We are comparing pointers, but the pointers are relative to a single string.
4076// Thus, this should always be deterministic.
Benjamin Kramer0d293e42013-09-22 14:09:50 +00004077static int rewritesSort(const AsmRewrite *AsmRewriteA,
4078 const AsmRewrite *AsmRewriteB) {
Chad Rosierabde6752013-02-13 18:38:58 +00004079 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4080 return -1;
4081 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4082 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004083
Chad Rosier6b369ce2013-04-08 17:43:47 +00004084 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4085 // rewrite to the same location. Make sure the SizeDirective rewrite is
4086 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4087 // ensures the sort algorithm is stable.
Jim Grosbach4a200922013-09-20 23:08:21 +00004088 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4089 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004090 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004091
Jim Grosbach4a200922013-09-20 23:08:21 +00004092 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4093 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004094 return 1;
Jim Grosbach4a200922013-09-20 23:08:21 +00004095 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004096}
4097
Jim Grosbach4a200922013-09-20 23:08:21 +00004098bool AsmParser::parseMSInlineAsm(
4099 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4100 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4101 SmallVectorImpl<std::string> &Constraints,
4102 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4103 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004104 SmallVector<void *, 4> InputDecls;
4105 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004106 SmallVector<bool, 4> InputDeclsAddressOf;
4107 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004108 SmallVector<std::string, 4> InputConstraints;
4109 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004110 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004111
Benjamin Kramer75234372013-02-15 20:37:21 +00004112 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004113
4114 // Prime the lexer.
4115 Lex();
4116
4117 // While we have input, parse each statement.
4118 unsigned InputIdx = 0;
4119 unsigned OutputIdx = 0;
4120 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004121 ParseStatementInfo Info(&AsmStrRewrites);
Jim Grosbach4a200922013-09-20 23:08:21 +00004122 if (parseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004123 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004124
Chad Rosier57498012012-12-12 22:45:52 +00004125 if (Info.ParseError)
4126 return true;
4127
Benjamin Kramer75234372013-02-15 20:37:21 +00004128 if (Info.Opcode == ~0U)
4129 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004130
Benjamin Kramer75234372013-02-15 20:37:21 +00004131 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004132
Benjamin Kramer75234372013-02-15 20:37:21 +00004133 // Build the list of clobbers, outputs and inputs.
4134 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4135 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004136
Benjamin Kramer75234372013-02-15 20:37:21 +00004137 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004138 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004139 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004140
Benjamin Kramer75234372013-02-15 20:37:21 +00004141 // Register operand.
4142 if (Operand->isReg() && !Operand->needAddressOf()) {
4143 unsigned NumDefs = Desc.getNumDefs();
4144 // Clobber.
4145 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4146 ClobberRegs.push_back(Operand->getReg());
4147 continue;
4148 }
4149
4150 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004151 StringRef SymName = Operand->getSymName();
4152 if (SymName.empty())
4153 continue;
4154
Chad Rosier087c3092013-04-22 22:12:12 +00004155 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004156 if (!OpDecl)
4157 continue;
4158
4159 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004160 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004161 if (isOutput) {
4162 ++InputIdx;
4163 OutputDecls.push_back(OpDecl);
4164 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4165 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004166 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004167 } else {
4168 InputDecls.push_back(OpDecl);
4169 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4170 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004171 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004172 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004173 }
4174 }
4175
4176 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004177 NumOutputs = OutputDecls.size();
4178 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004179
4180 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004181 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4182 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4183 ClobberRegs.end());
4184 Clobbers.assign(ClobberRegs.size(), std::string());
4185 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4186 raw_string_ostream OS(Clobbers[I]);
4187 IP->printRegName(OS, ClobberRegs[I]);
4188 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004189
4190 // Merge the various outputs and inputs. Output are expected first.
4191 if (NumOutputs || NumInputs) {
4192 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004193 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004194 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004195 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004196 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004197 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004198 }
4199 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004200 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004201 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004202 }
4203 }
4204
4205 // Build the IR assembly string.
4206 std::string AsmStringIR;
4207 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004208 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4209 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Jim Grosbach4a200922013-09-20 23:08:21 +00004210 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
Benjamin Kramer75234372013-02-15 20:37:21 +00004211 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4212 E = AsmStrRewrites.end();
4213 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004214 AsmRewriteKind Kind = (*I).Kind;
4215 if (Kind == AOK_Delete)
4216 continue;
4217
Chad Rosierb1f8c132012-10-18 15:49:34 +00004218 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004219 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004220
Chad Rosier023c8802013-03-19 17:32:17 +00004221 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004222 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004223 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004224 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004225
Chad Rosier5a719fc2012-10-23 17:43:43 +00004226 // Skip the original expression.
4227 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004228 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004229 continue;
4230 }
4231
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004232 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004233 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004234 switch (Kind) {
Jim Grosbach4a200922013-09-20 23:08:21 +00004235 default:
4236 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004237 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004238 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004239 break;
4240 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004241 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004242 break;
4243 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004244 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004245 break;
4246 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004247 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004248 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004249 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004250 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004251 default: break;
4252 case 8: OS << "byte ptr "; break;
4253 case 16: OS << "word ptr "; break;
4254 case 32: OS << "dword ptr "; break;
4255 case 64: OS << "qword ptr "; break;
4256 case 80: OS << "xword ptr "; break;
4257 case 128: OS << "xmmword ptr "; break;
4258 case 256: OS << "ymmword ptr "; break;
4259 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004260 break;
4261 case AOK_Emit:
4262 OS << ".byte";
4263 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004264 case AOK_Align: {
4265 unsigned Val = (*I).Val;
4266 OS << ".align " << Val;
4267
4268 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004269 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004270 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4271 break;
4272 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004273 case AOK_DotOperator:
4274 OS << (*I).Val;
4275 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004276 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004277
Chad Rosierb1f8c132012-10-18 15:49:34 +00004278 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004279 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004280 }
4281
4282 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004283 if (AsmStart != AsmEnd)
4284 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004285
4286 AsmString = OS.str();
4287 return false;
4288}
4289
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004290/// \brief Create an MCAsmParser instance.
Jim Grosbach4a200922013-09-20 23:08:21 +00004291MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4292 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004293 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004294}