blob: fbba77ef9c955ec61991b6696de6d4273fcb0581 [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 {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
100 /// Opcode - The opcode from the last parsed instruction.
101 unsigned Opcode;
102
Chad Rosier57498012012-12-12 22:45:52 +0000103 /// Error - Was there an error parsing the inline assembly?
104 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
Eli Bendersky6ee13082013-01-15 22:59:42 +0000141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// 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
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000146 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
151
Benjamin Kramera2b0c332013-08-04 09:06:29 +0000152 /// MacroLikeBodies - List of bodies of anonymous macros.
153 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
Preston Gurd7b6f2032012-09-19 20:36:12 +0000177 /// IsDarwin - is Darwin compatibility enabled?
178 bool IsDarwin;
179
Chad Rosier8f138d12012-10-15 17:19:13 +0000180 /// ParsingInlineAsm - 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 Grosbachcb2ae3d2013-02-20 22:21:35 +0000238 /// parseIdentifier - 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
Eli Friedman2128aae2012-10-22 23:58:19 +0000248 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000249 void EatToEndOfLine();
250 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000251
Kevin Enderby221514e2013-01-22 21:44:53 +0000252 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
253 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?
260 bool MacrosEnabled() {return MacrosEnabledFlag;}
261
262 /// \brief Control a flag in the parser that enables or disables macros.
263 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
264
265 /// \brief Lookup a previously defined macro.
266 /// \param Name Macro name.
267 /// \returns Pointer to macro. NULL if no such macro was defined.
268 const MCAsmMacro* LookupMacro(StringRef Name);
269
270 /// \brief Define a new macro with the given name and information.
271 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
272
273 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
274 void UndefineMacro(StringRef Name);
275
276 /// \brief Are we inside a macro instantiation?
277 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
278
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.
283 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
284
285 /// \brief Handle exit from macro instantiation.
286 void HandleMacroExit();
287
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.
291 bool ParseMacroArgument(MCAsmMacroArgument &MA,
292 AsmToken::TokenKind &ArgumentDelimiter);
293
294 /// \brief Parse all macro arguments for a given macro.
295 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
296
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000297 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000298 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
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000304 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
305 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000306 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
307 /// This returns true on failure.
308 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000309
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000310 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000311 /// current token is not set; clients should ensure Lex() is called
312 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000313 ///
314 /// \param InBuffer If not -1, should be the known buffer id that contains the
315 /// location.
316 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000317
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000318 /// \brief Parse up to the end of statement and a return the contents from the
319 /// current token until the end of the statement; the current token on exit
320 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000321 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000322
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000323 /// \brief Parse until the end of a statement or a comma is encountered,
324 /// return the contents from the current token up to the end or comma.
325 StringRef ParseStringToComma();
326
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000327 bool ParseAssignment(StringRef Name, bool allow_redef,
328 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000329
330 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000333 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000334
Eli Bendersky6ee13082013-01-15 22:59:42 +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,
345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
346 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
Eli Bendersky6ee13082013-01-15 22:59:42 +0000363 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000366
367 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000368 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000369 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000370 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000371 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000372 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000373 // ".set", ".equ", ".equiv"
374 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000375 bool ParseDirectiveOrg(); // ".org"
376 // ".align{,32}", ".p2align{,w,l}"
377 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
378
Eli Bendersky6ee13082013-01-15 22:59:42 +0000379 // ".file", ".line", ".loc", ".stabs"
380 bool ParseDirectiveFile(SMLoc DirectiveLoc);
381 bool ParseDirectiveLine();
382 bool ParseDirectiveLoc();
383 bool ParseDirectiveStabs();
384
385 // .cfi directives
386 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);
404
405 // macro directives
406 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
407 bool ParseDirectiveEndMacro(StringRef Directive);
408 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
409 bool ParseDirectiveMacrosOnOff(StringRef Directive);
410
Eli Bendersky4766ef42012-12-20 19:05:53 +0000411 // ".bundle_align_mode"
412 bool ParseDirectiveBundleAlignMode();
413 // ".bundle_lock"
414 bool ParseDirectiveBundleLock();
415 // ".bundle_unlock"
416 bool ParseDirectiveBundleUnlock();
417
Eli Bendersky6ee13082013-01-15 22:59:42 +0000418 // ".space", ".skip"
419 bool ParseDirectiveSpace(StringRef IDVal);
420
421 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
422 bool ParseDirectiveLEB128(bool Signed);
423
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000424 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
425 /// accepts a single symbol (which should be a label or an external).
426 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000427
428 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
429
430 bool ParseDirectiveAbort(); // ".abort"
431 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000432 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000433
434 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000435 // ".ifb" or ".ifnb", depending on ExpectBlank.
436 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000437 // ".ifc" or ".ifnc", depending on ExpectEqual.
438 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000439 // ".ifdef" or ".ifndef", depending on expect_defined
440 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000441 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
446 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
447 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000448
Rafael Espindola761cb062012-06-03 23:57:14 +0000449 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000450 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
451 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000452 raw_svector_ostream &OS);
453 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000454 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000455 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000456 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000457
Chad Rosier469b1442013-02-12 21:33:51 +0000458 // "_emit" or "__emit"
459 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
460 size_t Len);
461
462 // "align"
463 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 Grosbach1b84cce2011-08-16 18:33:49 +0000479AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000480 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000481 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000482 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000483 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000484 AssemblerDialect(~0U), IsDarwin(false), 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.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000515 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000516 ie = MacroMap.end(); it != ie; ++it)
517 delete it->getValue();
518
Daniel Dunbare4749702010-07-12 18:12:02 +0000519 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000520}
521
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000522void AsmParser::PrintMacroInstantiations() {
523 // Print the active macro instantiation stack.
524 for (std::vector<MacroInstantiation*>::const_reverse_iterator
525 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000526 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
527 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000528}
529
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000530bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000531 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000532 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000533 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000534 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000535 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000536}
537
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000538bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000539 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000540 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000541 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000542 return true;
543}
544
Sean Callananfd0b0282010-01-21 00:19:58 +0000545bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000546 std::string IncludedFile;
547 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000548 if (NewBuf == -1)
549 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000550
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000552
Sean Callananfd0b0282010-01-21 00:19:58 +0000553 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000554
Sean Callananfd0b0282010-01-21 00:19:58 +0000555 return false;
556}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000557
Sylvestre Ledruda2ed452013-05-14 23:36:24 +0000558/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000559/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000560/// returns true on failure.
561bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
562 std::string IncludedFile;
563 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
564 if (NewBuf == -1)
565 return true;
566
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000567 // Pick up the bytes from the file and emit them.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +0000568 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000569 return false;
570}
571
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000572void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
573 if (InBuffer != -1) {
574 CurBuffer = InBuffer;
575 } else {
576 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
577 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000578 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
579}
580
Sean Callananfd0b0282010-01-21 00:19:58 +0000581const AsmToken &AsmParser::Lex() {
582 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000583
Sean Callananfd0b0282010-01-21 00:19:58 +0000584 if (tok->is(AsmToken::Eof)) {
585 // If this is the end of an included file, pop the parent file off the
586 // include stack.
587 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
588 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000589 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000590 tok = &Lexer.Lex();
591 }
592 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000593
Sean Callananfd0b0282010-01-21 00:19:58 +0000594 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000595 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000596
Sean Callananfd0b0282010-01-21 00:19:58 +0000597 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000598}
599
Chris Lattner79180e22010-04-05 23:15:42 +0000600bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000601 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000602 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000603 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000604
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000605 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000606 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000607
608 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000609 AsmCond StartingCondState = TheCondState;
610
Kevin Enderby613b7572011-11-01 22:27:22 +0000611 // If we are generating dwarf for assembly source files save the initial text
612 // section and generate a .file directive.
613 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000614 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000615 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
616 getStreamer().EmitLabel(SectionStartSym);
617 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000618 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000619 StringRef(),
620 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000621 }
622
Chris Lattnerb717fb02009-07-02 21:53:43 +0000623 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000624 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000625 ParseStatementInfo Info;
626 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000627
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000628 // We had an error, validate that one was emitted and recover by skipping to
629 // the next line.
630 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000631 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000632 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000633
634 if (TheCondState.TheCond != StartingCondState.TheCond ||
635 TheCondState.Ignore != StartingCondState.Ignore)
636 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000637
638 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000639 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000640 getContext().getMCDwarfFiles();
641 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000642 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000643 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000644 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000645
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000646 // Check to see that all assembler local symbols were actually defined.
647 // Targets that don't do subsections via symbols may not want this, though,
648 // so conservatively exclude them. Only do this if we're finalizing, though,
649 // as otherwise we won't necessarilly have seen everything yet.
650 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
651 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
652 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
653 e = Symbols.end();
654 i != e; ++i) {
655 MCSymbol *Sym = i->getValue();
656 // Variable symbols may not be marked as defined, so check those
657 // explicitly. If we know it's a variable, we have a definition for
658 // the purposes of this check.
659 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
660 // FIXME: We would really like to refer back to where the symbol was
661 // first referenced for a source location. We need to add something
662 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000663 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
664 "assembler local symbol '" + Sym->getName() +
665 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000666 }
667 }
668
669
Chris Lattner79180e22010-04-05 23:15:42 +0000670 // Finalize the output stream if there are no errors and if the client wants
671 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000672 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000673 Out.Finish();
674
Chris Lattnerb717fb02009-07-02 21:53:43 +0000675 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000676}
677
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000678void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000679 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000680 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000681 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000682 }
683}
684
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000685/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
686void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000687 while (Lexer.isNot(AsmToken::EndOfStatement) &&
688 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000689 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000690
Chris Lattner2cf5f142009-06-22 01:29:09 +0000691 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000692 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000693 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000694}
695
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000696StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000697 const char *Start = getTok().getLoc().getPointer();
698
699 while (Lexer.isNot(AsmToken::EndOfStatement) &&
700 Lexer.isNot(AsmToken::Eof))
701 Lex();
702
703 const char *End = getTok().getLoc().getPointer();
704 return StringRef(Start, End - Start);
705}
Chris Lattnerc4193832009-06-22 05:51:26 +0000706
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000707StringRef AsmParser::ParseStringToComma() {
708 const char *Start = getTok().getLoc().getPointer();
709
710 while (Lexer.isNot(AsmToken::EndOfStatement) &&
711 Lexer.isNot(AsmToken::Comma) &&
712 Lexer.isNot(AsmToken::Eof))
713 Lex();
714
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
717}
718
Chris Lattner74ec1a32009-06-22 06:32:03 +0000719/// ParseParenExpr - Parse a paren expression and return it.
720/// NOTE: This assumes the leading '(' has already been consumed.
721///
722/// parenexpr ::= expr)
723///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000724bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000725 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000726 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000727 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000728 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000729 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000730 return false;
731}
Chris Lattnerc4193832009-06-22 05:51:26 +0000732
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000733/// ParseBracketExpr - Parse a bracket expression and return it.
734/// NOTE: This assumes the leading '[' has already been consumed.
735///
736/// bracketexpr ::= expr]
737///
738bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000739 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000740 if (Lexer.isNot(AsmToken::RBrac))
741 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000742 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000743 Lex();
744 return false;
745}
746
Chris Lattner74ec1a32009-06-22 06:32:03 +0000747/// ParsePrimaryExpr - Parse a primary expression and return it.
748/// primaryexpr ::= (parenexpr
749/// primaryexpr ::= symbol
750/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000751/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000752/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000753bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000754 SMLoc FirstTokenLoc = getLexer().getLoc();
755 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
756 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000757 default:
758 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000759 // If we have an error assume that we've already handled it.
760 case AsmToken::Error:
761 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000762 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000763 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000764 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000765 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000766 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000767 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000768 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000769 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000770 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000771 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000772 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000773 if (FirstTokenKind == AsmToken::Dollar)
774 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000775 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000776 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000777
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000778 EndLoc = SMLoc::getFromPointer(Identifier.end());
779
Daniel Dunbarfffff912009-10-16 01:34:54 +0000780 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000781 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000782 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000783
784 // Lookup the symbol variant if used.
785 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000786 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000787 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000788 if (Variant == MCSymbolRefExpr::VK_Invalid) {
789 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000790 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000791 }
792 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000793
Daniel Dunbarfffff912009-10-16 01:34:54 +0000794 // If this is an absolute variable reference, substitute it now to preserve
795 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000796 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000797 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000798 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000799
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000800 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000801 return false;
802 }
803
804 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000805 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000806 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000807 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000808 case AsmToken::Integer: {
809 SMLoc Loc = getTok().getLoc();
810 int64_t IntVal = getTok().getIntVal();
811 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000812 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000813 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000814 // Look for 'b' or 'f' following an Integer as a directional label
815 if (Lexer.getKind() == AsmToken::Identifier) {
816 StringRef IDVal = getTok().getString();
Ulrich Weigand151ad372013-06-20 16:24:17 +0000817 // Lookup the symbol variant if used.
818 std::pair<StringRef, StringRef> Split = IDVal.split('@');
819 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
820 if (Split.first.size() != IDVal.size()) {
821 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
822 if (Variant == MCSymbolRefExpr::VK_Invalid) {
823 Variant = MCSymbolRefExpr::VK_None;
824 return TokError("invalid variant '" + Split.second + "'");
825 }
Vladimir Medic7b0a7962013-08-20 13:33:18 +0000826 IDVal = Split.first;
Ulrich Weigand151ad372013-06-20 16:24:17 +0000827 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000828 if (IDVal == "f" || IDVal == "b"){
829 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
830 IDVal == "f" ? 1 : 0);
Ulrich Weigand151ad372013-06-20 16:24:17 +0000831 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000832 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000833 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000834 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000835 Lex(); // Eat identifier.
836 }
837 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000838 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000839 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000840 case AsmToken::Real: {
841 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000842 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000843 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000844 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000845 Lex(); // Eat token.
846 return false;
847 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000848 case AsmToken::Dot: {
849 // This is a '.' reference, which references the current PC. Emit a
850 // temporary label to the streamer and refer to it.
851 MCSymbol *Sym = Ctx.CreateTempSymbol();
852 Out.EmitLabel(Sym);
853 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000854 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000855 Lex(); // Eat identifier.
856 return false;
857 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000858 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000859 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000860 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000861 case AsmToken::LBrac:
862 if (!PlatformParser->HasBracketExpressions())
863 return TokError("brackets expression not supported on this target");
864 Lex(); // Eat the '['.
865 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000866 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000867 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000868 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000869 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000870 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000871 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000872 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000873 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000874 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000875 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000876 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000877 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000878 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000879 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +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::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000883 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000884 }
885}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000886
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000887bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000888 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000889 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000890}
891
Chad Rosierba69b362013-04-10 17:35:30 +0000892bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
893 return ParsePrimaryExpr(Res, EndLoc);
894}
895
Daniel Dunbarcceba832010-09-17 02:47:07 +0000896const MCExpr *
897AsmParser::ApplyModifierToExpr(const MCExpr *E,
898 MCSymbolRefExpr::VariantKind Variant) {
899 // Recurse over the given expression, rebuilding it to apply the given variant
900 // if there is exactly one symbol.
901 switch (E->getKind()) {
902 case MCExpr::Target:
903 case MCExpr::Constant:
904 return 0;
905
906 case MCExpr::SymbolRef: {
907 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
908
909 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
910 TokError("invalid variant on expression '" +
911 getTok().getIdentifier() + "' (already modified)");
912 return E;
913 }
914
915 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
916 }
917
918 case MCExpr::Unary: {
919 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
920 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
921 if (!Sub)
922 return 0;
923 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
924 }
925
926 case MCExpr::Binary: {
927 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
928 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
929 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
930
931 if (!LHS && !RHS)
932 return 0;
933
934 if (!LHS) LHS = BE->getLHS();
935 if (!RHS) RHS = BE->getRHS();
936
937 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
938 }
939 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000940
Craig Topper85814382012-02-07 05:05:23 +0000941 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000942}
943
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000944/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000945///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000946/// expr ::= expr &&,|| expr -> lowest.
947/// expr ::= expr |,^,&,! expr
948/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
949/// expr ::= expr <<,>> expr
950/// expr ::= expr +,- expr
951/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000952/// expr ::= primaryexpr
953///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000954bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000955 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000956 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000957 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
958 return true;
959
Daniel Dunbarcceba832010-09-17 02:47:07 +0000960 // As a special case, we support 'a op b @ modifier' by rewriting the
961 // expression to include the modifier. This is inefficient, but in general we
962 // expect users to use 'a@modifier op b'.
963 if (Lexer.getKind() == AsmToken::At) {
964 Lex();
965
966 if (Lexer.isNot(AsmToken::Identifier))
967 return TokError("unexpected symbol modifier following '@'");
968
969 MCSymbolRefExpr::VariantKind Variant =
970 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
971 if (Variant == MCSymbolRefExpr::VK_Invalid)
972 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
973
974 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
975 if (!ModifiedRes) {
976 return TokError("invalid modifier '" + getTok().getIdentifier() +
977 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000978 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000979
Daniel Dunbarcceba832010-09-17 02:47:07 +0000980 Res = ModifiedRes;
981 Lex();
982 }
983
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000984 // Try to constant fold it up front, if possible.
985 int64_t Value;
986 if (Res->EvaluateAsAbsolute(Value))
987 Res = MCConstantExpr::Create(Value, getContext());
988
989 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000990}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000991
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000992bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000993 Res = 0;
994 return ParseParenExpr(Res, EndLoc) ||
995 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000996}
997
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000998bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000999 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001000
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001001 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001002 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +00001003 return true;
1004
Daniel Dunbare00b0112009-10-16 01:57:52 +00001005 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001006 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +00001007
1008 return false;
1009}
1010
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001011static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001012 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001013 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001014 default:
1015 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001016
Jim Grosbachfbe16812011-08-20 16:24:13 +00001017 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001018 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001019 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001020 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001021 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001022 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001023 return 1;
1024
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001025
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001026 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001027 //
1028 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001029 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001030 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001031 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001032 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001033 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001034 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001035 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001036 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001037 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001038
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001039 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001040 case AsmToken::EqualEqual:
1041 Kind = MCBinaryExpr::EQ;
1042 return 3;
1043 case AsmToken::ExclaimEqual:
1044 case AsmToken::LessGreater:
1045 Kind = MCBinaryExpr::NE;
1046 return 3;
1047 case AsmToken::Less:
1048 Kind = MCBinaryExpr::LT;
1049 return 3;
1050 case AsmToken::LessEqual:
1051 Kind = MCBinaryExpr::LTE;
1052 return 3;
1053 case AsmToken::Greater:
1054 Kind = MCBinaryExpr::GT;
1055 return 3;
1056 case AsmToken::GreaterEqual:
1057 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001058 return 3;
1059
Jim Grosbachfbe16812011-08-20 16:24:13 +00001060 // Intermediate Precedence: <<, >>
1061 case AsmToken::LessLess:
1062 Kind = MCBinaryExpr::Shl;
1063 return 4;
1064 case AsmToken::GreaterGreater:
1065 Kind = MCBinaryExpr::Shr;
1066 return 4;
1067
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001068 // High Intermediate Precedence: +, -
1069 case AsmToken::Plus:
1070 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001071 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001072 case AsmToken::Minus:
1073 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001074 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001075
Jim Grosbachfbe16812011-08-20 16:24:13 +00001076 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001077 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001078 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001079 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001080 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001081 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001082 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001083 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001084 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001085 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 }
1087}
1088
1089
1090/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1091/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001092bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1093 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001094 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001095 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001096 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001097
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001098 // If the next token is lower precedence than we are allowed to eat, return
1099 // successfully with what we ate already.
1100 if (TokPrec < Precedence)
1101 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001102
Sean Callanan79ed1a82010-01-19 20:22:31 +00001103 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001104
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001105 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001106 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001107 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001108
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001109 // If BinOp binds less tightly with RHS than the operator after RHS, let
1110 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001111 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001112 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001113 if (TokPrec < NextTokPrec) {
Kevin Enderby88535dd2013-05-07 21:40:58 +00001114 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001115 }
1116
Daniel Dunbar475839e2009-06-29 20:37:27 +00001117 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001118 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001119 }
1120}
1121
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001122/// ParseStatement:
1123/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001124/// ::= Label* Directive ...Operands... EndOfStatement
1125/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001126bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001127 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001128 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001129 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001130 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001131 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001132
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001133 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001134 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001135 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001136 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001137 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001138 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001139 if (Lexer.is(AsmToken::Hash))
1140 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001141
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001142 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001143 if (Lexer.is(AsmToken::Integer)) {
1144 LocalLabelVal = getTok().getIntVal();
1145 if (LocalLabelVal < 0) {
1146 if (!TheCondState.Ignore)
1147 return TokError("unexpected token at start of statement");
1148 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001149 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001150 IDVal = getTok().getString();
1151 Lex(); // Consume the integer token to be used as an identifier token.
1152 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001153 if (!TheCondState.Ignore)
1154 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001155 }
1156 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001157 } else if (Lexer.is(AsmToken::Dot)) {
1158 // Treat '.' as a valid identifier in this context.
1159 Lex();
1160 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001161 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001162 if (!TheCondState.Ignore)
1163 return TokError("unexpected token at start of statement");
1164 IDVal = "";
1165 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001166
Chris Lattner7834fac2010-04-17 18:14:27 +00001167 // Handle conditional assembly here before checking for skipping. We
1168 // have to do this so that .endif isn't skipped in a ".if 0" block for
1169 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001171 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001172 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001173 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1174 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001175 switch (DirKind) {
1176 default:
1177 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001178 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001179 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001180 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001181 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001182 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001183 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001184 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001185 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001186 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001187 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001188 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001189 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001190 case DK_IFNDEF:
1191 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001192 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001193 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001194 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001195 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001196 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001197 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001198 return ParseDirectiveEndIf(IDLoc);
1199 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001200
Eli Benderskyed5df012013-01-16 19:32:36 +00001201 // Ignore the statement if in the middle of inactive conditional
1202 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001203 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001204 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001205 return false;
1206 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001207
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001208 // FIXME: Recurse on local labels?
1209
1210 // See what kind of statement we have.
1211 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001212 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001213 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001214
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001215 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001216 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001217
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001218 // Diagnose attempt to use '.' as a label.
1219 if (IDVal == ".")
1220 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1221
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001222 // Diagnose attempt to use a variable as a label.
1223 //
1224 // FIXME: Diagnostics. Note the location of the definition as a label.
1225 // FIXME: This doesn't diagnose assignment to a symbol which has been
1226 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001227 MCSymbol *Sym;
1228 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001229 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001230 else
1231 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001232 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001233 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001234
Daniel Dunbar959fd882009-08-26 22:13:22 +00001235 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001236 if (!ParsingInlineAsm)
1237 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001238
Kevin Enderby94c2e852011-12-09 18:09:40 +00001239 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001240 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001241 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001242 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1243 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001244
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001245 // Consume any end of statement token, if present, to avoid spurious
1246 // AddBlankLine calls().
1247 if (Lexer.is(AsmToken::EndOfStatement)) {
1248 Lex();
1249 if (Lexer.is(AsmToken::Eof))
1250 return false;
1251 }
1252
Eli Friedman2128aae2012-10-22 23:58:19 +00001253 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001254 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001255
Daniel Dunbar3f872332009-07-28 16:08:33 +00001256 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001257 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001258 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001259
Nico Weber4c4c7322011-01-28 03:04:41 +00001260 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001261
1262 default: // Normal instruction or directive.
1263 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001264 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001265
1266 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001267 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001268 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1269 return HandleMacroEntry(M, IDLoc);
1270 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001271
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001272 // Otherwise, we have a normal instruction or directive.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001273
Eli Bendersky6ee13082013-01-15 22:59:42 +00001274 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001275 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001276 // There are several entities interested in parsing directives:
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001277 //
Eli Bendersky6ee13082013-01-15 22:59:42 +00001278 // 1. The target-specific assembly parser. Some directives are target
1279 // specific or may potentially behave differently on certain targets.
1280 // 2. Asm parser extensions. For example, platform-specific parsers
1281 // (like the ELF parser) register themselves as extensions.
1282 // 3. The generic directive parser implemented by this class. These are
1283 // all the directives that behave in a target and platform independent
1284 // manner, or at least have a default behavior that's shared between
1285 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001286
Eli Bendersky6ee13082013-01-15 22:59:42 +00001287 // First query the target-specific parser. It will return 'true' if it
1288 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001289 if (!getTargetParser().ParseDirective(ID))
1290 return false;
1291
Eli Bendersky6ee13082013-01-15 22:59:42 +00001292 // Next, check the extention directive map to see if any extension has
1293 // registered itself to parse this directive.
1294 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1295 ExtensionDirectiveMap.lookup(IDVal);
1296 if (Handler.first)
1297 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1298
1299 // Finally, if no one else is interested in this directive, it must be
1300 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001301 switch (DirKind) {
1302 default:
1303 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001304 case DK_SET:
1305 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001308 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001309 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_ASCIZ:
1312 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001314 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001315 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001316 case DK_SHORT:
1317 case DK_VALUE:
1318 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_LONG:
1321 case DK_INT:
1322 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001324 case DK_QUAD:
1325 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_SINGLE:
1328 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001332 case DK_ALIGN: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001333 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1335 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001336 case DK_ALIGN32: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001337 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1339 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001343 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001347 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001348 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001349 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001350 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001359 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_GLOBL:
1362 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001363 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001364 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001365 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001366 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001382 case DK_COMM:
1383 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001384 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001385 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001386 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001387 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001388 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001389 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001390 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001391 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001392 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001393 case DK_CODE16:
1394 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001395 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001396 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001397 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001398 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001399 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001400 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001401 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001402 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001403 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001404 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001405 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001406 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001407 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001408 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001409 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001410 case DK_SLEB128:
1411 return ParseDirectiveLEB128(true);
1412 case DK_ULEB128:
1413 return ParseDirectiveLEB128(false);
1414 case DK_SPACE:
1415 case DK_SKIP:
1416 return ParseDirectiveSpace(IDVal);
1417 case DK_FILE:
1418 return ParseDirectiveFile(IDLoc);
1419 case DK_LINE:
1420 return ParseDirectiveLine();
1421 case DK_LOC:
1422 return ParseDirectiveLoc();
1423 case DK_STABS:
1424 return ParseDirectiveStabs();
1425 case DK_CFI_SECTIONS:
1426 return ParseDirectiveCFISections();
1427 case DK_CFI_STARTPROC:
1428 return ParseDirectiveCFIStartProc();
1429 case DK_CFI_ENDPROC:
1430 return ParseDirectiveCFIEndProc();
1431 case DK_CFI_DEF_CFA:
1432 return ParseDirectiveCFIDefCfa(IDLoc);
1433 case DK_CFI_DEF_CFA_OFFSET:
1434 return ParseDirectiveCFIDefCfaOffset();
1435 case DK_CFI_ADJUST_CFA_OFFSET:
1436 return ParseDirectiveCFIAdjustCfaOffset();
1437 case DK_CFI_DEF_CFA_REGISTER:
1438 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1439 case DK_CFI_OFFSET:
1440 return ParseDirectiveCFIOffset(IDLoc);
1441 case DK_CFI_REL_OFFSET:
1442 return ParseDirectiveCFIRelOffset(IDLoc);
1443 case DK_CFI_PERSONALITY:
1444 return ParseDirectiveCFIPersonalityOrLsda(true);
1445 case DK_CFI_LSDA:
1446 return ParseDirectiveCFIPersonalityOrLsda(false);
1447 case DK_CFI_REMEMBER_STATE:
1448 return ParseDirectiveCFIRememberState();
1449 case DK_CFI_RESTORE_STATE:
1450 return ParseDirectiveCFIRestoreState();
1451 case DK_CFI_SAME_VALUE:
1452 return ParseDirectiveCFISameValue(IDLoc);
1453 case DK_CFI_RESTORE:
1454 return ParseDirectiveCFIRestore(IDLoc);
1455 case DK_CFI_ESCAPE:
1456 return ParseDirectiveCFIEscape();
1457 case DK_CFI_SIGNAL_FRAME:
1458 return ParseDirectiveCFISignalFrame();
1459 case DK_CFI_UNDEFINED:
1460 return ParseDirectiveCFIUndefined(IDLoc);
1461 case DK_CFI_REGISTER:
1462 return ParseDirectiveCFIRegister(IDLoc);
1463 case DK_MACROS_ON:
1464 case DK_MACROS_OFF:
1465 return ParseDirectiveMacrosOnOff(IDVal);
1466 case DK_MACRO:
1467 return ParseDirectiveMacro(IDLoc);
1468 case DK_ENDM:
1469 case DK_ENDMACRO:
1470 return ParseDirectiveEndMacro(IDVal);
1471 case DK_PURGEM:
1472 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001473 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001474
Jim Grosbach686c0182012-05-01 18:38:27 +00001475 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001476 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001477
Chad Rosier469b1442013-02-12 21:33:51 +00001478 // __asm _emit or __asm __emit
1479 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1480 IDVal == "_EMIT" || IDVal == "__EMIT"))
1481 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1482
1483 // __asm align
1484 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1485 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001486
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001487 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001488
Chris Lattnera7f13542010-05-19 23:34:33 +00001489 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001490 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001491 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001492 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001493 IDLoc,
1494 Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001495 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001496
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001497 // Dump the parsed representation, if requested.
1498 if (getShowParsedOperands()) {
1499 SmallString<256> Str;
1500 raw_svector_ostream OS(Str);
1501 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001502 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001503 if (i != 0)
1504 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001505 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001506 }
1507 OS << "]";
1508
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001509 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001510 }
1511
Kevin Enderby613b7572011-11-01 22:27:22 +00001512 // If we are generating dwarf for assembly source files and the current
1513 // section is the initial text section then generate a .loc directive for
1514 // the instruction.
1515 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001516 getContext().getGenDwarfSection() ==
1517 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001518
Eli Benderskyed5df012013-01-16 19:32:36 +00001519 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001520
Eli Benderskyed5df012013-01-16 19:32:36 +00001521 // If we previously parsed a cpp hash file line comment then make sure the
1522 // current Dwarf File is for the CppHashFilename if not then emit the
1523 // Dwarf File table for it and adjust the line number for the .loc.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001524 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001525 getContext().getMCDwarfFiles();
1526 if (CppHashFilename.size() != 0) {
1527 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001528 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001529 getStreamer().EmitDwarfFileDirective(
1530 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001531
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001532 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
Kevin Enderbya8959492013-06-21 20:51:39 +00001533 // cache with the different Loc from the call above we save the last
1534 // info we queried here with SrcMgr.FindLineNumber().
1535 unsigned CppHashLocLineNo;
1536 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1537 CppHashLocLineNo = LastQueryLine;
1538 else {
1539 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1540 LastQueryLine = CppHashLocLineNo;
1541 LastQueryIDLoc = CppHashLoc;
1542 LastQueryBuffer = CppHashBuf;
1543 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001544 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001545 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001546
Kevin Enderby613b7572011-11-01 22:27:22 +00001547 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001548 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001549 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001550 StringRef());
1551 }
1552
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001553 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001554 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001555 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001556 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1557 Info.ParsedOperands,
1558 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001559 ParsingInlineAsm);
1560 }
Chris Lattner98986712010-01-14 22:21:20 +00001561
Chris Lattnercbf8a982010-09-11 16:18:25 +00001562 // Don't skip the rest of the line, the instruction parser is responsible for
1563 // that.
1564 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001565}
Chris Lattner9a023f72009-06-24 04:43:34 +00001566
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001567/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1568/// since they may not be able to be tokenized to get to the end of line token.
1569void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001570 if (!Lexer.is(AsmToken::EndOfStatement))
1571 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001572 // Eat EOL.
1573 Lex();
1574}
1575
1576/// ParseCppHashLineFilenameComment as this:
1577/// ::= # number "filename"
1578/// or just as a full line comment if it doesn't have a number and a string.
1579bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1580 Lex(); // Eat the hash token.
1581
1582 if (getLexer().isNot(AsmToken::Integer)) {
1583 // Consume the line since in cases it is not a well-formed line directive,
1584 // as if were simply a full line comment.
1585 EatToEndOfLine();
1586 return false;
1587 }
1588
1589 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001590 Lex();
1591
1592 if (getLexer().isNot(AsmToken::String)) {
1593 EatToEndOfLine();
1594 return false;
1595 }
1596
1597 StringRef Filename = getTok().getString();
1598 // Get rid of the enclosing quotes.
1599 Filename = Filename.substr(1, Filename.size()-2);
1600
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001601 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1602 CppHashLoc = L;
1603 CppHashFilename = Filename;
1604 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001605 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001606
1607 // Ignore any trailing characters, they're just comment.
1608 EatToEndOfLine();
1609 return false;
1610}
1611
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001612/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001613/// for the Filename and LineNo if any in the diagnostic.
1614void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1615 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1616 raw_ostream &OS = errs();
1617
1618 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1619 const SMLoc &DiagLoc = Diag.getLoc();
1620 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1621 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1622
1623 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1624 // before printing the message.
1625 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001626 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001627 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1628 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1629 }
1630
Eric Christopher2318ba12012-12-18 00:30:54 +00001631 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001632 // manager changed or buffer changed (like in a nested include) then just
1633 // print the normal diagnostic using its Filename and LineNo.
1634 if (!Parser->CppHashLineNumber ||
1635 &DiagSrcMgr != &Parser->SrcMgr ||
1636 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001637 if (Parser->SavedDiagHandler)
1638 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1639 else
1640 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001641 return;
1642 }
1643
Eric Christopher2318ba12012-12-18 00:30:54 +00001644 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001645 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1646 // the diagnostic.
1647 const std::string Filename = Parser->CppHashFilename;
1648
1649 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1650 int CppHashLocLineNo =
1651 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1652 int LineNo = Parser->CppHashLineNumber - 1 +
1653 (DiagLocLineNo - CppHashLocLineNo);
1654
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001655 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1656 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001657 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001658 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001659
Benjamin Kramer04a04262011-10-16 10:48:29 +00001660 if (Parser->SavedDiagHandler)
1661 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1662 else
1663 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001664}
1665
Rafael Espindola799aacf2012-08-21 18:29:30 +00001666// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1667// difference being that that function accepts '@' as part of identifiers and
1668// we can't do that. AsmLexer.cpp should probably be changed to handle
1669// '@' as a special case when needed.
1670static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001671 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1672 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001673}
1674
Rafael Espindola761cb062012-06-03 23:57:14 +00001675bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001676 const MCAsmMacroParameters &Parameters,
1677 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001678 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001679 unsigned NParameters = Parameters.size();
1680 if (NParameters != 0 && NParameters != A.size())
1681 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001682
Preston Gurd7b6f2032012-09-19 20:36:12 +00001683 // A macro without parameters is handled differently on Darwin:
1684 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001685 while (!Body.empty()) {
1686 // Scan for the next substitution.
1687 std::size_t End = Body.size(), Pos = 0;
1688 for (; Pos != End; ++Pos) {
1689 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001690 if (!NParameters) {
1691 // This macro has no parameters, look for $0, $1, etc.
1692 if (Body[Pos] != '$' || Pos + 1 == End)
1693 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001694
Rafael Espindola65366442011-06-05 02:43:45 +00001695 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001696 if (Next == '$' || Next == 'n' ||
1697 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001698 break;
1699 } else {
1700 // This macro has parameters, look for \foo, \bar, etc.
1701 if (Body[Pos] == '\\' && Pos + 1 != End)
1702 break;
1703 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001704 }
1705
1706 // Add the prefix.
1707 OS << Body.slice(0, Pos);
1708
1709 // Check if we reached the end.
1710 if (Pos == End)
1711 break;
1712
Rafael Espindola65366442011-06-05 02:43:45 +00001713 if (!NParameters) {
1714 switch (Body[Pos+1]) {
1715 // $$ => $
1716 case '$':
1717 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001718 break;
1719
Rafael Espindola65366442011-06-05 02:43:45 +00001720 // $n => number of arguments
1721 case 'n':
1722 OS << A.size();
1723 break;
1724
1725 // $[0-9] => argument
1726 default: {
1727 // Missing arguments are ignored.
1728 unsigned Index = Body[Pos+1] - '0';
1729 if (Index >= A.size())
1730 break;
1731
1732 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001733 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001734 ie = A[Index].end(); it != ie; ++it)
1735 OS << it->getString();
1736 break;
1737 }
1738 }
1739 Pos += 2;
1740 } else {
1741 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001742 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001743 ++I;
1744
1745 const char *Begin = Body.data() + Pos +1;
1746 StringRef Argument(Begin, I - (Pos +1));
1747 unsigned Index = 0;
1748 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001749 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001750 break;
1751
Preston Gurd7b6f2032012-09-19 20:36:12 +00001752 if (Index == NParameters) {
1753 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1754 Pos += 3;
1755 else {
1756 OS << '\\' << Argument;
1757 Pos = I;
1758 }
1759 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001760 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001761 ie = A[Index].end(); it != ie; ++it)
1762 if (it->getKind() == AsmToken::String)
1763 OS << it->getStringContents();
1764 else
1765 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001766
Preston Gurd7b6f2032012-09-19 20:36:12 +00001767 Pos += 1 + Argument.size();
1768 }
Rafael Espindola65366442011-06-05 02:43:45 +00001769 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001770 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001771 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001772 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001773
Rafael Espindola65366442011-06-05 02:43:45 +00001774 return false;
1775}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001776
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001777MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001778 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001779 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001780 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1781 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001782{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001783}
1784
Preston Gurd7b6f2032012-09-19 20:36:12 +00001785static bool IsOperator(AsmToken::TokenKind kind)
1786{
1787 switch (kind)
1788 {
1789 default:
1790 return false;
1791 case AsmToken::Plus:
1792 case AsmToken::Minus:
1793 case AsmToken::Tilde:
1794 case AsmToken::Slash:
1795 case AsmToken::Star:
1796 case AsmToken::Dot:
1797 case AsmToken::Equal:
1798 case AsmToken::EqualEqual:
1799 case AsmToken::Pipe:
1800 case AsmToken::PipePipe:
1801 case AsmToken::Caret:
1802 case AsmToken::Amp:
1803 case AsmToken::AmpAmp:
1804 case AsmToken::Exclaim:
1805 case AsmToken::ExclaimEqual:
1806 case AsmToken::Percent:
1807 case AsmToken::Less:
1808 case AsmToken::LessEqual:
1809 case AsmToken::LessLess:
1810 case AsmToken::LessGreater:
1811 case AsmToken::Greater:
1812 case AsmToken::GreaterEqual:
1813 case AsmToken::GreaterGreater:
1814 return true;
1815 }
1816}
1817
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001818bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001819 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001820 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001821 unsigned AddTokens = 0;
1822
1823 // gas accepts arguments separated by whitespace, except on Darwin
1824 if (!IsDarwin)
1825 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001826
1827 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001828 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1829 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001830 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001831 }
1832
1833 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1834 // Spaces and commas cannot be mixed to delimit parameters
1835 if (ArgumentDelimiter == AsmToken::Eof)
1836 ArgumentDelimiter = AsmToken::Comma;
1837 else if (ArgumentDelimiter != AsmToken::Comma) {
1838 Lexer.setSkipSpace(true);
1839 return TokError("expected ' ' for macro argument separator");
1840 }
1841 break;
1842 }
1843
1844 if (Lexer.is(AsmToken::Space)) {
1845 Lex(); // Eat spaces
1846
1847 // Spaces can delimit parameters, but could also be part an expression.
1848 // If the token after a space is an operator, add the token and the next
1849 // one into this argument
1850 if (ArgumentDelimiter == AsmToken::Space ||
1851 ArgumentDelimiter == AsmToken::Eof) {
1852 if (IsOperator(Lexer.getKind())) {
1853 // Check to see whether the token is used as an operator,
1854 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001855 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001856 if (*NextChar == ' ')
1857 AddTokens = 2;
1858 }
1859
1860 if (!AddTokens && ParenLevel == 0) {
1861 if (ArgumentDelimiter == AsmToken::Eof &&
1862 !IsOperator(Lexer.getKind()))
1863 ArgumentDelimiter = AsmToken::Space;
1864 break;
1865 }
1866 }
1867 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001868
1869 // HandleMacroEntry relies on not advancing the lexer here
1870 // to be able to fill in the remaining default parameter values
1871 if (Lexer.is(AsmToken::EndOfStatement))
1872 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001873
1874 // Adjust the current parentheses level.
1875 if (Lexer.is(AsmToken::LParen))
1876 ++ParenLevel;
1877 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1878 --ParenLevel;
1879
1880 // Append the token to the current argument list.
1881 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001882 if (AddTokens)
1883 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001884 Lex();
1885 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001886
1887 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001888 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001889 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001890 return false;
1891}
1892
1893// Parse the macro instantiation arguments.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001894bool AsmParser::ParseMacroArguments(const MCAsmMacro *M,
1895 MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001896 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001897 // Argument delimiter is initially unknown. It will be set by
1898 // ParseMacroArgument()
1899 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001900
1901 // Parse two kinds of macro invocations:
1902 // - macros defined without any parameters accept an arbitrary number of them
1903 // - macros defined with parameters accept at most that many of them
1904 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1905 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001906 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001907
Preston Gurd7b6f2032012-09-19 20:36:12 +00001908 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001909 return true;
1910
Preston Gurd6c9176a2012-09-19 20:29:04 +00001911 if (!MA.empty() || !NParameters)
1912 A.push_back(MA);
1913 else if (NParameters) {
1914 if (!M->Parameters[Parameter].second.empty())
1915 A.push_back(M->Parameters[Parameter].second);
1916 }
Jim Grosbach97146442012-07-30 22:44:17 +00001917
Preston Gurd6c9176a2012-09-19 20:29:04 +00001918 // At the end of the statement, fill in remaining arguments that have
1919 // default values. If there aren't any, then the next argument is
1920 // required but missing
1921 if (Lexer.is(AsmToken::EndOfStatement)) {
1922 if (NParameters && Parameter < NParameters - 1) {
1923 if (M->Parameters[Parameter + 1].second.empty())
1924 return TokError("macro argument '" +
1925 Twine(M->Parameters[Parameter + 1].first) +
1926 "' is missing");
1927 else
1928 continue;
1929 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001930 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001931 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001932
1933 if (Lexer.is(AsmToken::Comma))
1934 Lex();
1935 }
1936 return TokError("Too many arguments");
1937}
1938
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001939const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1940 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1941 return (I == MacroMap.end()) ? NULL : I->getValue();
1942}
1943
1944void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1945 MacroMap[Name] = new MCAsmMacro(Macro);
1946}
1947
1948void AsmParser::UndefineMacro(StringRef Name) {
1949 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1950 if (I != MacroMap.end()) {
1951 delete I->getValue();
1952 MacroMap.erase(I);
1953 }
1954}
1955
1956bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001957 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1958 // this, although we should protect against infinite loops.
1959 if (ActiveMacros.size() == 20)
1960 return TokError("macros cannot be nested more than 20 levels deep");
1961
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001962 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001963 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001964 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001965
Jim Grosbach97146442012-07-30 22:44:17 +00001966 // Remove any trailing empty arguments. Do this after-the-fact as we have
1967 // to keep empty arguments in the middle of the list or positionality
1968 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001969 while (!A.empty() && A.back().empty())
1970 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001971
Rafael Espindola65366442011-06-05 02:43:45 +00001972 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1973 // to hold the macro body with substitutions.
1974 SmallString<256> Buf;
1975 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001976 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001977
Rafael Espindola8a403d32012-08-08 14:51:03 +00001978 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001979 return true;
1980
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001981 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001982 // instantiation.
1983 OS << ".endmacro\n";
1984
Rafael Espindola65366442011-06-05 02:43:45 +00001985 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001986 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001987
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001988 // Create the macro instantiation object and add to the current macro
1989 // instantiation stack.
1990 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001991 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001992 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001993 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
2004void AsmParser::HandleMacroExit() {
2005 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +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
Rafael Espindolae71cc862012-01-28 05:57:00 +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: {
2017 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: {
2024 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002025 if (S.isVariable())
2026 return IsUsedIn(Sym, S.getVariableValue());
2027 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002028 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002029 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00002030 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002031 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002032
2033 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002034}
2035
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002036bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2037 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002038 // FIXME: Use better location, we should use proper tokens.
2039 SMLoc EqualLoc = Lexer.getLoc();
2040
Daniel Dunbar821e3332009-08-31 08:09:28 +00002041 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002042 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002043 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002044
Rafael Espindolae71cc862012-01-28 05:57:00 +00002045 // Note: we don't count b as used in "a = b". This is to allow
2046 // a = b
2047 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002048
Daniel Dunbar3f872332009-07-28 16:08:33 +00002049 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002050 return TokError("unexpected token in assignment");
2051
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002052 // Error on assignment to '.'.
2053 if (Name == ".") {
2054 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2055 "(use '.space' or '.org').)"));
2056 }
2057
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002058 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002059 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002060
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002061 // Validate that the LHS is allowed to be a variable (either it has not been
2062 // used as a symbol, or it is an absolute symbol).
2063 MCSymbol *Sym = getContext().LookupSymbol(Name);
2064 if (Sym) {
2065 // Diagnose assignment to a label.
2066 //
2067 // FIXME: Diagnostics. Note the location of the definition as a label.
2068 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002069 if (IsUsedIn(Sym, Value))
2070 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2071 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002072 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002073 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2074 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002075 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002076 return Error(EqualLoc, "redefinition of '" + Name + "'");
2077 else if (!Sym->isVariable())
2078 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002079 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002080 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2081 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002082
2083 // Don't count these checks as uses.
2084 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002085 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002086 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002087
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002088 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002089
2090 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002091 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002092 if (NoDeadStrip)
2093 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2094
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002095
2096 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.
2121 Res = StringRef(DollarLoc.getPointer(),
2122 getTok().getIdentifier().size() + 1);
2123 Lex();
2124 return false;
2125 }
2126
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002127 if (Lexer.isNot(AsmToken::Identifier) &&
2128 Lexer.isNot(AsmToken::String))
2129 return true;
2130
Sean Callanan18b83232010-01-19 21:44:56 +00002131 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002132
Sean Callanan79ed1a82010-01-19 20:22:31 +00002133 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002134
2135 return false;
2136}
2137
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002138/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002139/// ::= .equ identifier ',' expression
2140/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002141/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002142bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002143 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002144
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002145 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002146 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002147
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002148 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002149 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002150 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002151
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002152 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002153}
2154
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002155bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002156 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002157
2158 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002159 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002160 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2161 if (Str[i] != '\\') {
2162 Data += Str[i];
2163 continue;
2164 }
2165
2166 // Recognize escaped characters. Note that this escape semantics currently
2167 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2168 ++i;
2169 if (i == e)
2170 return TokError("unexpected backslash at end of string");
2171
2172 // Recognize octal sequences.
2173 if ((unsigned) (Str[i] - '0') <= 7) {
2174 // Consume up to three octal characters.
2175 unsigned Value = Str[i] - '0';
2176
2177 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2178 ++i;
2179 Value = Value * 8 + (Str[i] - '0');
2180
2181 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2182 ++i;
2183 Value = Value * 8 + (Str[i] - '0');
2184 }
2185 }
2186
2187 if (Value > 255)
2188 return TokError("invalid octal escape sequence (out of range)");
2189
2190 Data += (unsigned char) Value;
2191 continue;
2192 }
2193
2194 // Otherwise recognize individual escapes.
2195 switch (Str[i]) {
2196 default:
2197 // Just reject invalid escape sequences for now.
2198 return TokError("invalid escape sequence (unrecognized character)");
2199
2200 case 'b': Data += '\b'; break;
2201 case 'f': Data += '\f'; break;
2202 case 'n': Data += '\n'; break;
2203 case 'r': Data += '\r'; break;
2204 case 't': Data += '\t'; break;
2205 case '"': Data += '"'; break;
2206 case '\\': Data += '\\'; break;
2207 }
2208 }
2209
2210 return false;
2211}
2212
Daniel Dunbara0d14262009-06-24 23:30:00 +00002213/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002214/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2215bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002217 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002218
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002220 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002221 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002222
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002223 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002224 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002225 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002226
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002227 getStreamer().EmitBytes(Data);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002228 if (ZeroTerminated)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002229 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002230
Sean Callanan79ed1a82010-01-19 20:22:31 +00002231 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002232
2233 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 break;
2235
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002236 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002237 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002238 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239 }
2240 }
2241
Sean Callanan79ed1a82010-01-19 20:22:31 +00002242 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002243 return false;
2244}
2245
2246/// ParseDirectiveValue
2247/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2248bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002249 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002250 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002251
Daniel Dunbara0d14262009-06-24 23:30:00 +00002252 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002253 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002254 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002255 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002256 return true;
2257
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002258 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002259 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2260 assert(Size <= 8 && "Invalid size");
2261 uint64_t IntValue = MCE->getValue();
2262 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2263 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002264 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach254cf032011-06-29 16:05:14 +00002265 } else
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002266 getStreamer().EmitValue(Value, Size);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002267
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002268 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002270
Daniel Dunbara0d14262009-06-24 23:30:00 +00002271 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002272 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002273 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002274 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002275 }
2276 }
2277
Sean Callanan79ed1a82010-01-19 20:22:31 +00002278 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002279 return false;
2280}
2281
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002282/// ParseDirectiveRealValue
2283/// ::= (.single | .double) [ expression (, expression)* ]
2284bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2285 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002286 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002287
2288 for (;;) {
2289 // We don't truly support arithmetic on floating point expressions, so we
2290 // have to manually parse unary prefixes.
2291 bool IsNeg = false;
2292 if (getLexer().is(AsmToken::Minus)) {
2293 Lex();
2294 IsNeg = true;
2295 } else if (getLexer().is(AsmToken::Plus))
2296 Lex();
2297
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002298 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002299 getLexer().isNot(AsmToken::Real) &&
2300 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002301 return TokError("unexpected token in directive");
2302
2303 // Convert to an APFloat.
2304 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002305 StringRef IDVal = getTok().getString();
2306 if (getLexer().is(AsmToken::Identifier)) {
2307 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2308 Value = APFloat::getInf(Semantics);
2309 else if (!IDVal.compare_lower("nan"))
2310 Value = APFloat::getNaN(Semantics, false, ~0);
2311 else
2312 return TokError("invalid floating point literal");
2313 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002314 APFloat::opInvalidOp)
2315 return TokError("invalid floating point literal");
2316 if (IsNeg)
2317 Value.changeSign();
2318
2319 // Consume the numeric token.
2320 Lex();
2321
2322 // Emit the value as an integer.
2323 APInt AsInt = Value.bitcastToAPInt();
2324 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002325 AsInt.getBitWidth() / 8);
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002326
2327 if (getLexer().is(AsmToken::EndOfStatement))
2328 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002329
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002330 if (getLexer().isNot(AsmToken::Comma))
2331 return TokError("unexpected token in directive");
2332 Lex();
2333 }
2334 }
2335
2336 Lex();
2337 return false;
2338}
2339
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002340/// ParseDirectiveZero
2341/// ::= .zero expression
2342bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002343 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002344
2345 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002346 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002347 return true;
2348
Rafael Espindolae452b172010-10-05 19:42:57 +00002349 int64_t Val = 0;
2350 if (getLexer().is(AsmToken::Comma)) {
2351 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002352 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002353 return true;
2354 }
2355
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002356 if (getLexer().isNot(AsmToken::EndOfStatement))
2357 return TokError("unexpected token in '.zero' directive");
2358
2359 Lex();
2360
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002361 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002362
2363 return false;
2364}
2365
Daniel Dunbara0d14262009-06-24 23:30:00 +00002366/// ParseDirectiveFill
2367/// ::= .fill expression , expression , expression
2368bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002369 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002370
Daniel Dunbara0d14262009-06-24 23:30:00 +00002371 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002372 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002373 return true;
2374
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002375 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002376 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002377 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002378
Daniel Dunbara0d14262009-06-24 23:30:00 +00002379 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002380 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002381 return true;
2382
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002383 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002384 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002385 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002386
Daniel Dunbara0d14262009-06-24 23:30:00 +00002387 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002388 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002389 return true;
2390
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002391 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002392 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002393
Sean Callanan79ed1a82010-01-19 20:22:31 +00002394 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002395
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002396 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2397 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002398
2399 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002400 getStreamer().EmitIntValue(FillExpr, FillSize);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002401
2402 return false;
2403}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002404
2405/// ParseDirectiveOrg
2406/// ::= .org expression [ , expression ]
2407bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002408 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002409
Daniel Dunbar821e3332009-08-31 08:09:28 +00002410 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002411 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002412 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002413 return true;
2414
2415 // Parse optional fill expression.
2416 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002419 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002420 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002421
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002422 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002423 return true;
2424
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002425 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002426 return TokError("unexpected token in '.org' directive");
2427 }
2428
Sean Callanan79ed1a82010-01-19 20:22:31 +00002429 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002430
Jim Grosbachebd4c052012-01-27 00:37:08 +00002431 // Only limited forms of relocatable expressions are accepted here, it
2432 // has to be relative to the current section. The streamer will return
2433 // 'true' if the expression wasn't evaluatable.
2434 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2435 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002436
2437 return false;
2438}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002439
2440/// ParseDirectiveAlign
2441/// ::= {.align, ...} expression [ , expression [ , expression ]]
2442bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002443 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002444
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002445 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002446 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002447 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 return true;
2449
2450 SMLoc MaxBytesLoc;
2451 bool HasFillExpr = false;
2452 int64_t FillExpr = 0;
2453 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002454 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2455 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002456 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002457 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458
2459 // The fill expression can be omitted while specifying a maximum number of
2460 // alignment bytes, e.g:
2461 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002462 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002463 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002464 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002465 return true;
2466 }
2467
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002468 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2469 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002470 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002471 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002472
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002473 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002474 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002475 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002476
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002477 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002478 return TokError("unexpected token in directive");
2479 }
2480 }
2481
Sean Callanan79ed1a82010-01-19 20:22:31 +00002482 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002483
Daniel Dunbar648ac512010-05-17 21:54:30 +00002484 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002485 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002486
2487 // Compute alignment in bytes.
2488 if (IsPow2) {
2489 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002490 if (Alignment >= 32) {
2491 Error(AlignmentLoc, "invalid alignment value");
2492 Alignment = 31;
2493 }
2494
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002495 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002496 } else {
2497 // Reject alignments that aren't a power of two, for gas compatibility.
2498 if (!isPowerOf2_64(Alignment))
2499 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002500 }
2501
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002502 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002503 if (MaxBytesLoc.isValid()) {
2504 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002505 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2506 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002507 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002508 }
2509
2510 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002511 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2512 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002513 MaxBytesToFill = 0;
2514 }
2515 }
2516
Daniel Dunbar648ac512010-05-17 21:54:30 +00002517 // Check whether we should use optimal code alignment for this .align
2518 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002519 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002520 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2521 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002522 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002523 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002524 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002525 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2526 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002527 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002528
2529 return false;
2530}
2531
Eli Bendersky6ee13082013-01-15 22:59:42 +00002532/// ParseDirectiveFile
2533/// ::= .file [number] filename
2534/// ::= .file number directory filename
2535bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2536 // FIXME: I'm not sure what this is.
2537 int64_t FileNumber = -1;
2538 SMLoc FileNumberLoc = getLexer().getLoc();
2539 if (getLexer().is(AsmToken::Integer)) {
2540 FileNumber = getTok().getIntVal();
2541 Lex();
2542
2543 if (FileNumber < 1)
2544 return TokError("file number less than one");
2545 }
2546
2547 if (getLexer().isNot(AsmToken::String))
2548 return TokError("unexpected token in '.file' directive");
2549
2550 // Usually the directory and filename together, otherwise just the directory.
2551 StringRef Path = getTok().getString();
2552 Path = Path.substr(1, Path.size()-2);
2553 Lex();
2554
2555 StringRef Directory;
2556 StringRef Filename;
2557 if (getLexer().is(AsmToken::String)) {
2558 if (FileNumber == -1)
2559 return TokError("explicit path specified, but no file number");
2560 Filename = getTok().getString();
2561 Filename = Filename.substr(1, Filename.size()-2);
2562 Directory = Path;
2563 Lex();
2564 } else {
2565 Filename = Path;
2566 }
2567
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '.file' directive");
2570
2571 if (FileNumber == -1)
2572 getStreamer().EmitFileDirective(Filename);
2573 else {
2574 if (getContext().getGenDwarfForAssembly() == true)
2575 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2576 "used to generate dwarf debug info for assembly code");
2577
2578 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2579 Error(FileNumberLoc, "file number already allocated");
2580 }
2581
2582 return false;
2583}
2584
2585/// ParseDirectiveLine
2586/// ::= .line [number]
2587bool AsmParser::ParseDirectiveLine() {
2588 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2589 if (getLexer().isNot(AsmToken::Integer))
2590 return TokError("unexpected token in '.line' directive");
2591
2592 int64_t LineNumber = getTok().getIntVal();
2593 (void) LineNumber;
2594 Lex();
2595
2596 // FIXME: Do something with the .line.
2597 }
2598
2599 if (getLexer().isNot(AsmToken::EndOfStatement))
2600 return TokError("unexpected token in '.line' directive");
2601
2602 return false;
2603}
2604
2605/// ParseDirectiveLoc
2606/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2607/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2608/// The first number is a file number, must have been previously assigned with
2609/// a .file directive, the second number is the line number and optionally the
2610/// third number is a column position (zero if not specified). The remaining
2611/// optional items are .loc sub-directives.
2612bool AsmParser::ParseDirectiveLoc() {
2613 if (getLexer().isNot(AsmToken::Integer))
2614 return TokError("unexpected token in '.loc' directive");
2615 int64_t FileNumber = getTok().getIntVal();
2616 if (FileNumber < 1)
2617 return TokError("file number less than one in '.loc' directive");
2618 if (!getContext().isValidDwarfFileNumber(FileNumber))
2619 return TokError("unassigned file number in '.loc' directive");
2620 Lex();
2621
2622 int64_t LineNumber = 0;
2623 if (getLexer().is(AsmToken::Integer)) {
2624 LineNumber = getTok().getIntVal();
2625 if (LineNumber < 1)
2626 return TokError("line number less than one in '.loc' directive");
2627 Lex();
2628 }
2629
2630 int64_t ColumnPos = 0;
2631 if (getLexer().is(AsmToken::Integer)) {
2632 ColumnPos = getTok().getIntVal();
2633 if (ColumnPos < 0)
2634 return TokError("column position less than zero in '.loc' directive");
2635 Lex();
2636 }
2637
2638 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2639 unsigned Isa = 0;
2640 int64_t Discriminator = 0;
2641 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2642 for (;;) {
2643 if (getLexer().is(AsmToken::EndOfStatement))
2644 break;
2645
2646 StringRef Name;
2647 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002648 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002649 return TokError("unexpected token in '.loc' directive");
2650
2651 if (Name == "basic_block")
2652 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2653 else if (Name == "prologue_end")
2654 Flags |= DWARF2_FLAG_PROLOGUE_END;
2655 else if (Name == "epilogue_begin")
2656 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2657 else if (Name == "is_stmt") {
2658 Loc = getTok().getLoc();
2659 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002660 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002661 return true;
2662 // The expression must be the constant 0 or 1.
2663 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2664 int Value = MCE->getValue();
2665 if (Value == 0)
2666 Flags &= ~DWARF2_FLAG_IS_STMT;
2667 else if (Value == 1)
2668 Flags |= DWARF2_FLAG_IS_STMT;
2669 else
2670 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002671 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002672 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2673 }
Craig Topperefa703d2013-04-22 04:22:40 +00002674 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002675 Loc = getTok().getLoc();
2676 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002677 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002678 return true;
2679 // The expression must be a constant greater or equal to 0.
2680 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2681 int Value = MCE->getValue();
2682 if (Value < 0)
2683 return Error(Loc, "isa number less than zero");
2684 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002685 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002686 return Error(Loc, "isa number not a constant value");
2687 }
Craig Topperefa703d2013-04-22 04:22:40 +00002688 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002689 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002690 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002691 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002692 return Error(Loc, "unknown sub-directive in '.loc' directive");
2693 }
2694
2695 if (getLexer().is(AsmToken::EndOfStatement))
2696 break;
2697 }
2698 }
2699
2700 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2701 Isa, Discriminator, StringRef());
2702
2703 return false;
2704}
2705
2706/// ParseDirectiveStabs
2707/// ::= .stabs string, number, number, number
2708bool AsmParser::ParseDirectiveStabs() {
2709 return TokError("unsupported directive '.stabs'");
2710}
2711
2712/// ParseDirectiveCFISections
2713/// ::= .cfi_sections section [, section]
2714bool AsmParser::ParseDirectiveCFISections() {
2715 StringRef Name;
2716 bool EH = false;
2717 bool Debug = false;
2718
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002719 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002720 return TokError("Expected an identifier");
2721
2722 if (Name == ".eh_frame")
2723 EH = true;
2724 else if (Name == ".debug_frame")
2725 Debug = true;
2726
2727 if (getLexer().is(AsmToken::Comma)) {
2728 Lex();
2729
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002730 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002731 return TokError("Expected an identifier");
2732
2733 if (Name == ".eh_frame")
2734 EH = true;
2735 else if (Name == ".debug_frame")
2736 Debug = true;
2737 }
2738
2739 getStreamer().EmitCFISections(EH, Debug);
2740 return false;
2741}
2742
2743/// ParseDirectiveCFIStartProc
2744/// ::= .cfi_startproc
2745bool AsmParser::ParseDirectiveCFIStartProc() {
2746 getStreamer().EmitCFIStartProc();
2747 return false;
2748}
2749
2750/// ParseDirectiveCFIEndProc
2751/// ::= .cfi_endproc
2752bool AsmParser::ParseDirectiveCFIEndProc() {
2753 getStreamer().EmitCFIEndProc();
2754 return false;
2755}
2756
2757/// ParseRegisterOrRegisterNumber - parse register name or number.
2758bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2759 SMLoc DirectiveLoc) {
2760 unsigned RegNo;
2761
2762 if (getLexer().isNot(AsmToken::Integer)) {
2763 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2764 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002765 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002766 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002767 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002768
2769 return false;
2770}
2771
2772/// ParseDirectiveCFIDefCfa
2773/// ::= .cfi_def_cfa register, offset
2774bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2775 int64_t Register = 0;
2776 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2777 return true;
2778
2779 if (getLexer().isNot(AsmToken::Comma))
2780 return TokError("unexpected token in directive");
2781 Lex();
2782
2783 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002784 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002785 return true;
2786
2787 getStreamer().EmitCFIDefCfa(Register, Offset);
2788 return false;
2789}
2790
2791/// ParseDirectiveCFIDefCfaOffset
2792/// ::= .cfi_def_cfa_offset offset
2793bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2794 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002795 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002796 return true;
2797
2798 getStreamer().EmitCFIDefCfaOffset(Offset);
2799 return false;
2800}
2801
2802/// ParseDirectiveCFIRegister
2803/// ::= .cfi_register register, register
2804bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2805 int64_t Register1 = 0;
2806 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2807 return true;
2808
2809 if (getLexer().isNot(AsmToken::Comma))
2810 return TokError("unexpected token in directive");
2811 Lex();
2812
2813 int64_t Register2 = 0;
2814 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2815 return true;
2816
2817 getStreamer().EmitCFIRegister(Register1, Register2);
2818 return false;
2819}
2820
2821/// ParseDirectiveCFIAdjustCfaOffset
2822/// ::= .cfi_adjust_cfa_offset adjustment
2823bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2824 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002825 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002826 return true;
2827
2828 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2829 return false;
2830}
2831
2832/// ParseDirectiveCFIDefCfaRegister
2833/// ::= .cfi_def_cfa_register register
2834bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2835 int64_t Register = 0;
2836 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2837 return true;
2838
2839 getStreamer().EmitCFIDefCfaRegister(Register);
2840 return false;
2841}
2842
2843/// ParseDirectiveCFIOffset
2844/// ::= .cfi_offset register, offset
2845bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2846 int64_t Register = 0;
2847 int64_t Offset = 0;
2848
2849 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2850 return true;
2851
2852 if (getLexer().isNot(AsmToken::Comma))
2853 return TokError("unexpected token in directive");
2854 Lex();
2855
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002856 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002857 return true;
2858
2859 getStreamer().EmitCFIOffset(Register, Offset);
2860 return false;
2861}
2862
2863/// ParseDirectiveCFIRelOffset
2864/// ::= .cfi_rel_offset register, offset
2865bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2866 int64_t Register = 0;
2867
2868 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2869 return true;
2870
2871 if (getLexer().isNot(AsmToken::Comma))
2872 return TokError("unexpected token in directive");
2873 Lex();
2874
2875 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002876 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002877 return true;
2878
2879 getStreamer().EmitCFIRelOffset(Register, Offset);
2880 return false;
2881}
2882
2883static bool isValidEncoding(int64_t Encoding) {
2884 if (Encoding & ~0xff)
2885 return false;
2886
2887 if (Encoding == dwarf::DW_EH_PE_omit)
2888 return true;
2889
2890 const unsigned Format = Encoding & 0xf;
2891 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2892 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2893 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2894 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2895 return false;
2896
2897 const unsigned Application = Encoding & 0x70;
2898 if (Application != dwarf::DW_EH_PE_absptr &&
2899 Application != dwarf::DW_EH_PE_pcrel)
2900 return false;
2901
2902 return true;
2903}
2904
2905/// ParseDirectiveCFIPersonalityOrLsda
2906/// IsPersonality true for cfi_personality, false for cfi_lsda
2907/// ::= .cfi_personality encoding, [symbol_name]
2908/// ::= .cfi_lsda encoding, [symbol_name]
2909bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2910 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002911 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002912 return true;
2913 if (Encoding == dwarf::DW_EH_PE_omit)
2914 return false;
2915
2916 if (!isValidEncoding(Encoding))
2917 return TokError("unsupported encoding.");
2918
2919 if (getLexer().isNot(AsmToken::Comma))
2920 return TokError("unexpected token in directive");
2921 Lex();
2922
2923 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002924 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002925 return TokError("expected identifier in directive");
2926
2927 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2928
2929 if (IsPersonality)
2930 getStreamer().EmitCFIPersonality(Sym, Encoding);
2931 else
2932 getStreamer().EmitCFILsda(Sym, Encoding);
2933 return false;
2934}
2935
2936/// ParseDirectiveCFIRememberState
2937/// ::= .cfi_remember_state
2938bool AsmParser::ParseDirectiveCFIRememberState() {
2939 getStreamer().EmitCFIRememberState();
2940 return false;
2941}
2942
2943/// ParseDirectiveCFIRestoreState
2944/// ::= .cfi_remember_state
2945bool AsmParser::ParseDirectiveCFIRestoreState() {
2946 getStreamer().EmitCFIRestoreState();
2947 return false;
2948}
2949
2950/// ParseDirectiveCFISameValue
2951/// ::= .cfi_same_value register
2952bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2953 int64_t Register = 0;
2954
2955 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2956 return true;
2957
2958 getStreamer().EmitCFISameValue(Register);
2959 return false;
2960}
2961
2962/// ParseDirectiveCFIRestore
2963/// ::= .cfi_restore register
2964bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2965 int64_t Register = 0;
2966 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2967 return true;
2968
2969 getStreamer().EmitCFIRestore(Register);
2970 return false;
2971}
2972
2973/// ParseDirectiveCFIEscape
2974/// ::= .cfi_escape expression[,...]
2975bool AsmParser::ParseDirectiveCFIEscape() {
2976 std::string Values;
2977 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002978 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002979 return true;
2980
2981 Values.push_back((uint8_t)CurrValue);
2982
2983 while (getLexer().is(AsmToken::Comma)) {
2984 Lex();
2985
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002986 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002987 return true;
2988
2989 Values.push_back((uint8_t)CurrValue);
2990 }
2991
2992 getStreamer().EmitCFIEscape(Values);
2993 return false;
2994}
2995
2996/// ParseDirectiveCFISignalFrame
2997/// ::= .cfi_signal_frame
2998bool AsmParser::ParseDirectiveCFISignalFrame() {
2999 if (getLexer().isNot(AsmToken::EndOfStatement))
3000 return Error(getLexer().getLoc(),
3001 "unexpected token in '.cfi_signal_frame'");
3002
3003 getStreamer().EmitCFISignalFrame();
3004 return false;
3005}
3006
3007/// ParseDirectiveCFIUndefined
3008/// ::= .cfi_undefined register
3009bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3010 int64_t Register = 0;
3011
3012 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3013 return true;
3014
3015 getStreamer().EmitCFIUndefined(Register);
3016 return false;
3017}
3018
3019/// ParseDirectiveMacrosOnOff
3020/// ::= .macros_on
3021/// ::= .macros_off
3022bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3023 if (getLexer().isNot(AsmToken::EndOfStatement))
3024 return Error(getLexer().getLoc(),
3025 "unexpected token in '" + Directive + "' directive");
3026
3027 SetMacrosEnabled(Directive == ".macros_on");
3028 return false;
3029}
3030
3031/// ParseDirectiveMacro
3032/// ::= .macro name [parameters]
3033bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3034 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003035 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003036 return TokError("expected identifier in '.macro' directive");
3037
3038 MCAsmMacroParameters Parameters;
3039 // Argument delimiter is initially unknown. It will be set by
3040 // ParseMacroArgument()
3041 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3042 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3043 for (;;) {
3044 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003045 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003046 return TokError("expected identifier in '.macro' directive");
3047
3048 if (getLexer().is(AsmToken::Equal)) {
3049 Lex();
3050 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3051 return true;
3052 }
3053
3054 Parameters.push_back(Parameter);
3055
3056 if (getLexer().is(AsmToken::Comma))
3057 Lex();
3058 else if (getLexer().is(AsmToken::EndOfStatement))
3059 break;
3060 }
3061 }
3062
3063 // Eat the end of statement.
3064 Lex();
3065
3066 AsmToken EndToken, StartToken = getTok();
3067
3068 // Lex the macro definition.
3069 for (;;) {
3070 // Check whether we have reached the end of the file.
3071 if (getLexer().is(AsmToken::Eof))
3072 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3073
3074 // Otherwise, check whether we have reach the .endmacro.
3075 if (getLexer().is(AsmToken::Identifier) &&
3076 (getTok().getIdentifier() == ".endm" ||
3077 getTok().getIdentifier() == ".endmacro")) {
3078 EndToken = getTok();
3079 Lex();
3080 if (getLexer().isNot(AsmToken::EndOfStatement))
3081 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3082 "' directive");
3083 break;
3084 }
3085
3086 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003087 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003088 }
3089
3090 if (LookupMacro(Name)) {
3091 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3092 }
3093
3094 const char *BodyStart = StartToken.getLoc().getPointer();
3095 const char *BodyEnd = EndToken.getLoc().getPointer();
3096 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003097 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003098 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3099 return false;
3100}
3101
Kevin Enderby221514e2013-01-22 21:44:53 +00003102/// CheckForBadMacro
3103///
3104/// With the support added for named parameters there may be code out there that
3105/// is transitioning from positional parameters. In versions of gas that did
3106/// not support named parameters they would be ignored on the macro defintion.
3107/// But to support both styles of parameters this is not possible so if a macro
3108/// defintion has named parameters but does not use them and has what appears
3109/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3110/// warning that the positional parameter found in body which have no effect.
3111/// Hoping the developer will either remove the named parameters from the macro
3112/// definiton so the positional parameters get used if that was what was
3113/// intended or change the macro to use the named parameters. It is possible
3114/// this warning will trigger when the none of the named parameters are used
3115/// and the strings like $1 are infact to simply to be passed trough unchanged.
3116void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3117 StringRef Body,
3118 MCAsmMacroParameters Parameters) {
3119 // If this macro is not defined with named parameters the warning we are
3120 // checking for here doesn't apply.
3121 unsigned NParameters = Parameters.size();
3122 if (NParameters == 0)
3123 return;
3124
3125 bool NamedParametersFound = false;
3126 bool PositionalParametersFound = false;
3127
3128 // Look at the body of the macro for use of both the named parameters and what
3129 // are likely to be positional parameters. This is what expandMacro() is
3130 // doing when it finds the parameters in the body.
3131 while (!Body.empty()) {
3132 // Scan for the next possible parameter.
3133 std::size_t End = Body.size(), Pos = 0;
3134 for (; Pos != End; ++Pos) {
3135 // Check for a substitution or escape.
3136 // This macro is defined with parameters, look for \foo, \bar, etc.
3137 if (Body[Pos] == '\\' && Pos + 1 != End)
3138 break;
3139
3140 // This macro should have parameters, but look for $0, $1, ..., $n too.
3141 if (Body[Pos] != '$' || Pos + 1 == End)
3142 continue;
3143 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003144 if (Next == '$' || Next == 'n' ||
3145 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003146 break;
3147 }
3148
3149 // Check if we reached the end.
3150 if (Pos == End)
3151 break;
3152
3153 if (Body[Pos] == '$') {
3154 switch (Body[Pos+1]) {
3155 // $$ => $
3156 case '$':
3157 break;
3158
3159 // $n => number of arguments
3160 case 'n':
3161 PositionalParametersFound = true;
3162 break;
3163
3164 // $[0-9] => argument
3165 default: {
3166 PositionalParametersFound = true;
3167 break;
3168 }
3169 }
3170 Pos += 2;
3171 } else {
3172 unsigned I = Pos + 1;
3173 while (isIdentifierChar(Body[I]) && I + 1 != End)
3174 ++I;
3175
3176 const char *Begin = Body.data() + Pos +1;
3177 StringRef Argument(Begin, I - (Pos +1));
3178 unsigned Index = 0;
3179 for (; Index < NParameters; ++Index)
3180 if (Parameters[Index].first == Argument)
3181 break;
3182
3183 if (Index == NParameters) {
3184 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3185 Pos += 3;
3186 else {
3187 Pos = I;
3188 }
3189 } else {
3190 NamedParametersFound = true;
3191 Pos += 1 + Argument.size();
3192 }
3193 }
3194 // Update the scan point.
3195 Body = Body.substr(Pos);
3196 }
3197
3198 if (!NamedParametersFound && PositionalParametersFound)
3199 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3200 "used in macro body, possible positional parameter "
3201 "found in body which will have no effect");
3202}
3203
Eli Bendersky6ee13082013-01-15 22:59:42 +00003204/// ParseDirectiveEndMacro
3205/// ::= .endm
3206/// ::= .endmacro
3207bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3208 if (getLexer().isNot(AsmToken::EndOfStatement))
3209 return TokError("unexpected token in '" + Directive + "' directive");
3210
3211 // If we are inside a macro instantiation, terminate the current
3212 // instantiation.
3213 if (InsideMacroInstantiation()) {
3214 HandleMacroExit();
3215 return false;
3216 }
3217
3218 // Otherwise, this .endmacro is a stray entry in the file; well formed
3219 // .endmacro directives are handled during the macro definition parsing.
3220 return TokError("unexpected '" + Directive + "' in file, "
3221 "no current macro definition");
3222}
3223
3224/// ParseDirectivePurgeMacro
3225/// ::= .purgem
3226bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3227 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003228 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003229 return TokError("expected identifier in '.purgem' directive");
3230
3231 if (getLexer().isNot(AsmToken::EndOfStatement))
3232 return TokError("unexpected token in '.purgem' directive");
3233
3234 if (!LookupMacro(Name))
3235 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3236
3237 UndefineMacro(Name);
3238 return false;
3239}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003240
3241/// ParseDirectiveBundleAlignMode
3242/// ::= {.bundle_align_mode} expression
3243bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003244 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003245
3246 // Expect a single argument: an expression that evaluates to a constant
3247 // in the inclusive range 0-30.
3248 SMLoc ExprLoc = getLexer().getLoc();
3249 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003250 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003251 return true;
3252 else if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return TokError("unexpected token after expression in"
3254 " '.bundle_align_mode' directive");
3255 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3256 return Error(ExprLoc,
3257 "invalid bundle alignment size (expected between 0 and 30)");
3258
3259 Lex();
3260
3261 // Because of AlignSizePow2's verified range we can safely truncate it to
3262 // unsigned.
3263 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3264 return false;
3265}
3266
3267/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003268/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003269bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003270 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003271 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003272
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003273 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3274 StringRef Option;
3275 SMLoc Loc = getTok().getLoc();
3276 const char *kInvalidOptionError =
3277 "invalid option for '.bundle_lock' directive";
3278
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003279 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003280 return Error(Loc, kInvalidOptionError);
3281
3282 if (Option != "align_to_end")
3283 return Error(Loc, kInvalidOptionError);
3284 else if (getLexer().isNot(AsmToken::EndOfStatement))
3285 return Error(Loc,
3286 "unexpected token after '.bundle_lock' directive option");
3287 AlignToEnd = true;
3288 }
3289
Eli Bendersky4766ef42012-12-20 19:05:53 +00003290 Lex();
3291
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003292 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003293 return false;
3294}
3295
3296/// ParseDirectiveBundleLock
3297/// ::= {.bundle_lock}
3298bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003299 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003300
3301 if (getLexer().isNot(AsmToken::EndOfStatement))
3302 return TokError("unexpected token in '.bundle_unlock' directive");
3303 Lex();
3304
3305 getStreamer().EmitBundleUnlock();
3306 return false;
3307}
3308
Eli Bendersky6ee13082013-01-15 22:59:42 +00003309/// ParseDirectiveSpace
3310/// ::= (.skip | .space) expression [ , expression ]
3311bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003312 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003313
3314 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003315 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003316 return true;
3317
3318 int64_t FillExpr = 0;
3319 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3320 if (getLexer().isNot(AsmToken::Comma))
3321 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3322 Lex();
3323
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003324 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003325 return true;
3326
3327 if (getLexer().isNot(AsmToken::EndOfStatement))
3328 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3329 }
3330
3331 Lex();
3332
3333 if (NumBytes <= 0)
3334 return TokError("invalid number of bytes in '" +
3335 Twine(IDVal) + "' directive");
3336
3337 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00003338 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003339
3340 return false;
3341}
3342
3343/// ParseDirectiveLEB128
3344/// ::= (.sleb128 | .uleb128) expression
3345bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003346 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003347 const MCExpr *Value;
3348
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003349 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003350 return true;
3351
3352 if (getLexer().isNot(AsmToken::EndOfStatement))
3353 return TokError("unexpected token in directive");
3354
3355 if (Signed)
3356 getStreamer().EmitSLEB128Value(Value);
3357 else
3358 getStreamer().EmitULEB128Value(Value);
3359
3360 return false;
3361}
3362
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003363/// ParseDirectiveSymbolAttribute
3364/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003365bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003366 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003367 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003368 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003369 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003370
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003371 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003372 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003373
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003374 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003375
Jim Grosbach10ec6502011-09-15 17:56:49 +00003376 // Assembler local symbols don't make any sense here. Complain loudly.
3377 if (Sym->isTemporary())
3378 return Error(Loc, "non-local symbol required in directive");
3379
Saleem Abdulrasool1c9cd022013-08-09 01:52:03 +00003380 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3381 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003382
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003383 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003384 break;
3385
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003386 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003387 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003388 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003389 }
3390 }
3391
Sean Callanan79ed1a82010-01-19 20:22:31 +00003392 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003393 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003394}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003395
3396/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003397/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3398bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003399 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003400
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003401 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003402 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003403 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003404 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003405
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003406 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003407 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003408
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003409 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003410 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003411 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003412
3413 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003414 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003415 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003416 return true;
3417
3418 int64_t Pow2Alignment = 0;
3419 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003420 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003421 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003422 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003423 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003424 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003425
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003426 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3427 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003428 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3429
Chris Lattner258281d2010-01-19 06:22:22 +00003430 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003431 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3432 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003433 if (!isPowerOf2_64(Pow2Alignment))
3434 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3435 Pow2Alignment = Log2_64(Pow2Alignment);
3436 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003437 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003438
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003439 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003440 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003441
Sean Callanan79ed1a82010-01-19 20:22:31 +00003442 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003443
Chris Lattner1fc3d752009-07-09 17:25:12 +00003444 // NOTE: a size of zero for a .comm should create a undefined symbol
3445 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003446 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003447 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3448 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003449
Eric Christopherc260a3e2010-05-14 01:38:54 +00003450 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003451 // may internally end up wanting an alignment in bytes.
3452 // FIXME: Diagnose overflow.
3453 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003454 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3455 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003456
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003457 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003458 return Error(IDLoc, "invalid symbol redefinition");
3459
Chris Lattner1fc3d752009-07-09 17:25:12 +00003460 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003461 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003462 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003463 return false;
3464 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003465
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003466 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003467 return false;
3468}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003469
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003470/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003471/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003472bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003473 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003474 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003475
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003476 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003477 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003478 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003479
Sean Callanan79ed1a82010-01-19 20:22:31 +00003480 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003481
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003482 if (Str.empty())
3483 Error(Loc, ".abort detected. Assembly stopping.");
3484 else
3485 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003486 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003487
3488 return false;
3489}
Kevin Enderby71148242009-07-14 21:35:03 +00003490
Kevin Enderby1f049b22009-07-14 23:21:55 +00003491/// ParseDirectiveInclude
3492/// ::= .include "filename"
3493bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003494 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003495 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003496
Sean Callanan18b83232010-01-19 21:44:56 +00003497 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003498 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003499 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003500
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003501 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003502 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003503
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003504 // Strip the quotes.
3505 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003506
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003507 // Attempt to switch the lexer to the included file before consuming the end
3508 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003509 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003510 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003511 return true;
3512 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003513
3514 return false;
3515}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003516
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003517/// ParseDirectiveIncbin
3518/// ::= .incbin "filename"
3519bool AsmParser::ParseDirectiveIncbin() {
3520 if (getLexer().isNot(AsmToken::String))
3521 return TokError("expected string in '.incbin' directive");
3522
3523 std::string Filename = getTok().getString();
3524 SMLoc IncbinLoc = getLexer().getLoc();
3525 Lex();
3526
3527 if (getLexer().isNot(AsmToken::EndOfStatement))
3528 return TokError("unexpected token in '.incbin' directive");
3529
3530 // Strip the quotes.
3531 Filename = Filename.substr(1, Filename.size()-2);
3532
3533 // Attempt to process the included file.
3534 if (ProcessIncbinFile(Filename)) {
3535 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3536 return true;
3537 }
3538
3539 return false;
3540}
3541
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003542/// ParseDirectiveIf
3543/// ::= .if expression
3544bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003545 TheCondStack.push_back(TheCondState);
3546 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003547 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003548 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003549 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003550 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003551 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003552 return true;
3553
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003554 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003555 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003556
Sean Callanan79ed1a82010-01-19 20:22:31 +00003557 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003558
3559 TheCondState.CondMet = ExprValue;
3560 TheCondState.Ignore = !TheCondState.CondMet;
3561 }
3562
3563 return false;
3564}
3565
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003566/// ParseDirectiveIfb
3567/// ::= .ifb string
3568bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3569 TheCondStack.push_back(TheCondState);
3570 TheCondState.TheCond = AsmCond::IfCond;
3571
Benjamin Kramer29739e72012-05-12 16:52:21 +00003572 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003573 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003574 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003575 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003576
3577 if (getLexer().isNot(AsmToken::EndOfStatement))
3578 return TokError("unexpected token in '.ifb' directive");
3579
3580 Lex();
3581
3582 TheCondState.CondMet = ExpectBlank == Str.empty();
3583 TheCondState.Ignore = !TheCondState.CondMet;
3584 }
3585
3586 return false;
3587}
3588
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003589/// ParseDirectiveIfc
3590/// ::= .ifc string1, string2
3591bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3592 TheCondStack.push_back(TheCondState);
3593 TheCondState.TheCond = AsmCond::IfCond;
3594
Benjamin Kramer29739e72012-05-12 16:52:21 +00003595 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003596 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003597 } else {
3598 StringRef Str1 = ParseStringToComma();
3599
3600 if (getLexer().isNot(AsmToken::Comma))
3601 return TokError("unexpected token in '.ifc' directive");
3602
3603 Lex();
3604
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003605 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003606
3607 if (getLexer().isNot(AsmToken::EndOfStatement))
3608 return TokError("unexpected token in '.ifc' directive");
3609
3610 Lex();
3611
3612 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3613 TheCondState.Ignore = !TheCondState.CondMet;
3614 }
3615
3616 return false;
3617}
3618
3619/// ParseDirectiveIfdef
3620/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003621bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3622 StringRef Name;
3623 TheCondStack.push_back(TheCondState);
3624 TheCondState.TheCond = AsmCond::IfCond;
3625
3626 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003627 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003628 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003629 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003630 return TokError("expected identifier after '.ifdef'");
3631
3632 Lex();
3633
3634 MCSymbol *Sym = getContext().LookupSymbol(Name);
3635
3636 if (expect_defined)
3637 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3638 else
3639 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3640 TheCondState.Ignore = !TheCondState.CondMet;
3641 }
3642
3643 return false;
3644}
3645
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003646/// ParseDirectiveElseIf
3647/// ::= .elseif expression
3648bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3649 if (TheCondState.TheCond != AsmCond::IfCond &&
3650 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003651 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3652 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003653 TheCondState.TheCond = AsmCond::ElseIfCond;
3654
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003655 bool LastIgnoreState = false;
3656 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003657 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003658 if (LastIgnoreState || TheCondState.CondMet) {
3659 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003660 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003661 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003662 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003663 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003664 return true;
3665
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003666 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003667 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003668
Sean Callanan79ed1a82010-01-19 20:22:31 +00003669 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003670 TheCondState.CondMet = ExprValue;
3671 TheCondState.Ignore = !TheCondState.CondMet;
3672 }
3673
3674 return false;
3675}
3676
3677/// ParseDirectiveElse
3678/// ::= .else
3679bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003680 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003681 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003682
Sean Callanan79ed1a82010-01-19 20:22:31 +00003683 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003684
3685 if (TheCondState.TheCond != AsmCond::IfCond &&
3686 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003687 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3688 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003689 TheCondState.TheCond = AsmCond::ElseCond;
3690 bool LastIgnoreState = false;
3691 if (!TheCondStack.empty())
3692 LastIgnoreState = TheCondStack.back().Ignore;
3693 if (LastIgnoreState || TheCondState.CondMet)
3694 TheCondState.Ignore = true;
3695 else
3696 TheCondState.Ignore = false;
3697
3698 return false;
3699}
3700
3701/// ParseDirectiveEndIf
3702/// ::= .endif
3703bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003704 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003705 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003706
Sean Callanan79ed1a82010-01-19 20:22:31 +00003707 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003708
3709 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3710 TheCondStack.empty())
3711 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3712 ".else");
3713 if (!TheCondStack.empty()) {
3714 TheCondState = TheCondStack.back();
3715 TheCondStack.pop_back();
3716 }
3717
3718 return false;
3719}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003720
Eli Bendersky6ee13082013-01-15 22:59:42 +00003721void AsmParser::initializeDirectiveKindMap() {
3722 DirectiveKindMap[".set"] = DK_SET;
3723 DirectiveKindMap[".equ"] = DK_EQU;
3724 DirectiveKindMap[".equiv"] = DK_EQUIV;
3725 DirectiveKindMap[".ascii"] = DK_ASCII;
3726 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3727 DirectiveKindMap[".string"] = DK_STRING;
3728 DirectiveKindMap[".byte"] = DK_BYTE;
3729 DirectiveKindMap[".short"] = DK_SHORT;
3730 DirectiveKindMap[".value"] = DK_VALUE;
3731 DirectiveKindMap[".2byte"] = DK_2BYTE;
3732 DirectiveKindMap[".long"] = DK_LONG;
3733 DirectiveKindMap[".int"] = DK_INT;
3734 DirectiveKindMap[".4byte"] = DK_4BYTE;
3735 DirectiveKindMap[".quad"] = DK_QUAD;
3736 DirectiveKindMap[".8byte"] = DK_8BYTE;
3737 DirectiveKindMap[".single"] = DK_SINGLE;
3738 DirectiveKindMap[".float"] = DK_FLOAT;
3739 DirectiveKindMap[".double"] = DK_DOUBLE;
3740 DirectiveKindMap[".align"] = DK_ALIGN;
3741 DirectiveKindMap[".align32"] = DK_ALIGN32;
3742 DirectiveKindMap[".balign"] = DK_BALIGN;
3743 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3744 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3745 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3746 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3747 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3748 DirectiveKindMap[".org"] = DK_ORG;
3749 DirectiveKindMap[".fill"] = DK_FILL;
3750 DirectiveKindMap[".zero"] = DK_ZERO;
3751 DirectiveKindMap[".extern"] = DK_EXTERN;
3752 DirectiveKindMap[".globl"] = DK_GLOBL;
3753 DirectiveKindMap[".global"] = DK_GLOBAL;
3754 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3755 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3756 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3757 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3758 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3759 DirectiveKindMap[".reference"] = DK_REFERENCE;
3760 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3761 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3762 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3763 DirectiveKindMap[".comm"] = DK_COMM;
3764 DirectiveKindMap[".common"] = DK_COMMON;
3765 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3766 DirectiveKindMap[".abort"] = DK_ABORT;
3767 DirectiveKindMap[".include"] = DK_INCLUDE;
3768 DirectiveKindMap[".incbin"] = DK_INCBIN;
3769 DirectiveKindMap[".code16"] = DK_CODE16;
3770 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3771 DirectiveKindMap[".rept"] = DK_REPT;
3772 DirectiveKindMap[".irp"] = DK_IRP;
3773 DirectiveKindMap[".irpc"] = DK_IRPC;
3774 DirectiveKindMap[".endr"] = DK_ENDR;
3775 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3776 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3777 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3778 DirectiveKindMap[".if"] = DK_IF;
3779 DirectiveKindMap[".ifb"] = DK_IFB;
3780 DirectiveKindMap[".ifnb"] = DK_IFNB;
3781 DirectiveKindMap[".ifc"] = DK_IFC;
3782 DirectiveKindMap[".ifnc"] = DK_IFNC;
3783 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3784 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3785 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3786 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3787 DirectiveKindMap[".else"] = DK_ELSE;
3788 DirectiveKindMap[".endif"] = DK_ENDIF;
3789 DirectiveKindMap[".skip"] = DK_SKIP;
3790 DirectiveKindMap[".space"] = DK_SPACE;
3791 DirectiveKindMap[".file"] = DK_FILE;
3792 DirectiveKindMap[".line"] = DK_LINE;
3793 DirectiveKindMap[".loc"] = DK_LOC;
3794 DirectiveKindMap[".stabs"] = DK_STABS;
3795 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3796 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3797 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3798 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3799 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3800 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3801 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3802 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3803 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3804 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3805 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3806 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3807 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3808 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3809 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3810 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3811 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3812 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3813 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3814 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3815 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3816 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3817 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3818 DirectiveKindMap[".macro"] = DK_MACRO;
3819 DirectiveKindMap[".endm"] = DK_ENDM;
3820 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3821 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003822}
3823
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003824
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003825MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003826 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003827
Rafael Espindola761cb062012-06-03 23:57:14 +00003828 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003829 for (;;) {
3830 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003831 if (getLexer().is(AsmToken::Eof)) {
3832 Error(DirectiveLoc, "no matching '.endr' in definition");
3833 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003834 }
3835
Rafael Espindola761cb062012-06-03 23:57:14 +00003836 if (Lexer.is(AsmToken::Identifier) &&
3837 (getTok().getIdentifier() == ".rept")) {
3838 ++NestLevel;
3839 }
3840
3841 // Otherwise, check whether we have reached the .endr.
3842 if (Lexer.is(AsmToken::Identifier) &&
3843 getTok().getIdentifier() == ".endr") {
3844 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003845 EndToken = getTok();
3846 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003847 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3848 TokError("unexpected token in '.endr' directive");
3849 return 0;
3850 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003851 break;
3852 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003853 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003854 }
3855
Rafael Espindola761cb062012-06-03 23:57:14 +00003856 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003857 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003858 }
3859
3860 const char *BodyStart = StartToken.getLoc().getPointer();
3861 const char *BodyEnd = EndToken.getLoc().getPointer();
3862 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3863
Rafael Espindola761cb062012-06-03 23:57:14 +00003864 // We Are Anonymous.
3865 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003866 MCAsmMacroParameters Parameters;
Benjamin Kramera2b0c332013-08-04 09:06:29 +00003867 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3868 return &MacroLikeBodies.back();
Rafael Espindola761cb062012-06-03 23:57:14 +00003869}
3870
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003871void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003872 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003873 OS << ".endr\n";
3874
3875 MemoryBuffer *Instantiation =
3876 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3877
Rafael Espindola761cb062012-06-03 23:57:14 +00003878 // Create the macro instantiation object and add to the current macro
3879 // instantiation stack.
3880 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003881 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003882 getTok().getLoc(),
3883 Instantiation);
3884 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003885
Rafael Espindola761cb062012-06-03 23:57:14 +00003886 // Jump to the macro instantiation and prime the lexer.
3887 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3888 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3889 Lex();
3890}
3891
3892bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3893 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003894 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003895 return TokError("unexpected token in '.rept' directive");
3896
3897 if (Count < 0)
3898 return TokError("Count is negative");
3899
3900 if (Lexer.isNot(AsmToken::EndOfStatement))
3901 return TokError("unexpected token in '.rept' directive");
3902
3903 // Eat the end of statement.
3904 Lex();
3905
3906 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003907 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003908 if (!M)
3909 return true;
3910
3911 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3912 // to hold the macro body with substitutions.
3913 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003914 MCAsmMacroParameters Parameters;
3915 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003916 raw_svector_ostream OS(Buf);
3917 while (Count--) {
3918 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3919 return true;
3920 }
3921 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003922
3923 return false;
3924}
3925
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003926/// ParseDirectiveIrp
3927/// ::= .irp symbol,values
3928bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003929 MCAsmMacroParameters Parameters;
3930 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003931
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003932 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003933 return TokError("expected identifier in '.irp' directive");
3934
3935 Parameters.push_back(Parameter);
3936
3937 if (Lexer.isNot(AsmToken::Comma))
3938 return TokError("expected comma in '.irp' directive");
3939
3940 Lex();
3941
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003942 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003943 if (ParseMacroArguments(0, A))
3944 return true;
3945
3946 // Eat the end of statement.
3947 Lex();
3948
3949 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003950 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003951 if (!M)
3952 return true;
3953
3954 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3955 // to hold the macro body with substitutions.
3956 SmallString<256> Buf;
3957 raw_svector_ostream OS(Buf);
3958
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003959 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3960 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003961 Args.push_back(*i);
3962
3963 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3964 return true;
3965 }
3966
3967 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3968
3969 return false;
3970}
3971
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003972/// ParseDirectiveIrpc
3973/// ::= .irpc symbol,values
3974bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003975 MCAsmMacroParameters Parameters;
3976 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003977
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003978 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003979 return TokError("expected identifier in '.irpc' directive");
3980
3981 Parameters.push_back(Parameter);
3982
3983 if (Lexer.isNot(AsmToken::Comma))
3984 return TokError("expected comma in '.irpc' directive");
3985
3986 Lex();
3987
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003988 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003989 if (ParseMacroArguments(0, A))
3990 return true;
3991
3992 if (A.size() != 1 || A.front().size() != 1)
3993 return TokError("unexpected token in '.irpc' directive");
3994
3995 // Eat the end of statement.
3996 Lex();
3997
3998 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003999 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004000 if (!M)
4001 return true;
4002
4003 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4004 // to hold the macro body with substitutions.
4005 SmallString<256> Buf;
4006 raw_svector_ostream OS(Buf);
4007
4008 StringRef Values = A.front().front().getString();
4009 std::size_t I, End = Values.size();
4010 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00004011 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004012 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
4013
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004014 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004015 Args.push_back(Arg);
4016
4017 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4018 return true;
4019 }
4020
4021 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
4022
4023 return false;
4024}
4025
Rafael Espindola761cb062012-06-03 23:57:14 +00004026bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4027 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004028 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004029
4030 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004031 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004032 assert(getLexer().is(AsmToken::EndOfStatement));
4033
Rafael Espindola761cb062012-06-03 23:57:14 +00004034 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004035 return false;
4036}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004037
Benjamin Kramer75234372013-02-15 20:37:21 +00004038bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4039 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004040 const MCExpr *Value;
4041 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004042 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004043 return true;
4044 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4045 if (!MCE)
4046 return Error(ExprLoc, "unexpected expression in _emit");
4047 uint64_t IntValue = MCE->getValue();
4048 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4049 return Error(ExprLoc, "literal value out of range for directive");
4050
Chad Rosier469b1442013-02-12 21:33:51 +00004051 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4052 return false;
4053}
4054
4055bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4056 const MCExpr *Value;
4057 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004058 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004059 return true;
4060 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4061 if (!MCE)
4062 return Error(ExprLoc, "unexpected expression in align");
4063 uint64_t IntValue = MCE->getValue();
4064 if (!isPowerOf2_64(IntValue))
4065 return Error(ExprLoc, "literal value not a power of two greater then zero");
4066
Benjamin Kramer75234372013-02-15 20:37:21 +00004067 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4068 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004069 return false;
4070}
4071
Chad Rosier19aa3e32013-02-13 21:27:17 +00004072// We are comparing pointers, but the pointers are relative to a single string.
4073// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004074static int RewritesSort(const void *A, const void *B) {
4075 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4076 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004077 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4078 return -1;
4079 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4080 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004081
Chad Rosier6b369ce2013-04-08 17:43:47 +00004082 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4083 // rewrite to the same location. Make sure the SizeDirective rewrite is
4084 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4085 // ensures the sort algorithm is stable.
4086 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4087 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004088 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004089
4090 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4091 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004092 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004093 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004094}
4095
Benjamin Kramer75234372013-02-15 20:37:21 +00004096bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004097AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004098 unsigned &NumOutputs, unsigned &NumInputs,
4099 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4100 SmallVectorImpl<std::string> &Constraints,
4101 SmallVectorImpl<std::string> &Clobbers,
4102 const MCInstrInfo *MII,
4103 const MCInstPrinter *IP,
4104 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004105 SmallVector<void *, 4> InputDecls;
4106 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004107 SmallVector<bool, 4> InputDeclsAddressOf;
4108 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004109 SmallVector<std::string, 4> InputConstraints;
4110 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004111 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004112
Benjamin Kramer75234372013-02-15 20:37:21 +00004113 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004114
4115 // Prime the lexer.
4116 Lex();
4117
4118 // While we have input, parse each statement.
4119 unsigned InputIdx = 0;
4120 unsigned OutputIdx = 0;
4121 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004122 ParseStatementInfo Info(&AsmStrRewrites);
4123 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004124 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004125
Chad Rosier57498012012-12-12 22:45:52 +00004126 if (Info.ParseError)
4127 return true;
4128
Benjamin Kramer75234372013-02-15 20:37:21 +00004129 if (Info.Opcode == ~0U)
4130 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004131
Benjamin Kramer75234372013-02-15 20:37:21 +00004132 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004133
Benjamin Kramer75234372013-02-15 20:37:21 +00004134 // Build the list of clobbers, outputs and inputs.
4135 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4136 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004137
Benjamin Kramer75234372013-02-15 20:37:21 +00004138 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004139 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004140 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004141
Benjamin Kramer75234372013-02-15 20:37:21 +00004142 // Register operand.
4143 if (Operand->isReg() && !Operand->needAddressOf()) {
4144 unsigned NumDefs = Desc.getNumDefs();
4145 // Clobber.
4146 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4147 ClobberRegs.push_back(Operand->getReg());
4148 continue;
4149 }
4150
4151 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004152 StringRef SymName = Operand->getSymName();
4153 if (SymName.empty())
4154 continue;
4155
Chad Rosier087c3092013-04-22 22:12:12 +00004156 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004157 if (!OpDecl)
4158 continue;
4159
4160 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004161 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004162 if (isOutput) {
4163 ++InputIdx;
4164 OutputDecls.push_back(OpDecl);
4165 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4166 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004167 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004168 } else {
4169 InputDecls.push_back(OpDecl);
4170 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4171 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004172 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004173 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004174 }
4175 }
4176
4177 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004178 NumOutputs = OutputDecls.size();
4179 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004180
4181 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004182 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4183 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4184 ClobberRegs.end());
4185 Clobbers.assign(ClobberRegs.size(), std::string());
4186 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4187 raw_string_ostream OS(Clobbers[I]);
4188 IP->printRegName(OS, ClobberRegs[I]);
4189 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004190
4191 // Merge the various outputs and inputs. Output are expected first.
4192 if (NumOutputs || NumInputs) {
4193 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004194 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004195 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004196 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004197 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004198 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004199 }
4200 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004201 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004202 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004203 }
4204 }
4205
4206 // Build the IR assembly string.
4207 std::string AsmStringIR;
4208 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004209 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4210 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004211 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4212 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4213 E = AsmStrRewrites.end();
4214 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004215 AsmRewriteKind Kind = (*I).Kind;
4216 if (Kind == AOK_Delete)
4217 continue;
4218
Chad Rosierb1f8c132012-10-18 15:49:34 +00004219 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004220 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004221
Chad Rosier023c8802013-03-19 17:32:17 +00004222 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004223 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004224 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004225 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004226
Chad Rosier5a719fc2012-10-23 17:43:43 +00004227 // Skip the original expression.
4228 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004229 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004230 continue;
4231 }
4232
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004233 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004234 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004235 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004236 default: 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 Grosbach1b84cce2011-08-16 18:33:49 +00004291MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004292 MCContext &C, MCStreamer &Out,
4293 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004294 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004295}