blob: 31a09a967c60769ba3126e734ab79abb393d73c9 [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,
Kevin Enderby4f066b62013-08-28 17:50:59 +0000345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
358 DK_CFI_REGISTER,
359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000361 };
362
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) {
Joerg Sonnenberger66b71392013-08-27 20:23:19 +0000899 // Ask the target implementation about this expression first.
900 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
901 if (NewE)
902 return NewE;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000903 // Recurse over the given expression, rebuilding it to apply the given variant
904 // if there is exactly one symbol.
905 switch (E->getKind()) {
906 case MCExpr::Target:
907 case MCExpr::Constant:
908 return 0;
909
910 case MCExpr::SymbolRef: {
911 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
912
913 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
914 TokError("invalid variant on expression '" +
915 getTok().getIdentifier() + "' (already modified)");
916 return E;
917 }
918
919 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
920 }
921
922 case MCExpr::Unary: {
923 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
924 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
925 if (!Sub)
926 return 0;
927 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
928 }
929
930 case MCExpr::Binary: {
931 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
932 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
933 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
934
935 if (!LHS && !RHS)
936 return 0;
937
938 if (!LHS) LHS = BE->getLHS();
939 if (!RHS) RHS = BE->getRHS();
940
941 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
942 }
943 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000944
Craig Topper85814382012-02-07 05:05:23 +0000945 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000946}
947
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000948/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000949///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000950/// expr ::= expr &&,|| expr -> lowest.
951/// expr ::= expr |,^,&,! expr
952/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
953/// expr ::= expr <<,>> expr
954/// expr ::= expr +,- expr
955/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000956/// expr ::= primaryexpr
957///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000958bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000959 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000960 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000961 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
962 return true;
963
Daniel Dunbarcceba832010-09-17 02:47:07 +0000964 // As a special case, we support 'a op b @ modifier' by rewriting the
965 // expression to include the modifier. This is inefficient, but in general we
966 // expect users to use 'a@modifier op b'.
967 if (Lexer.getKind() == AsmToken::At) {
968 Lex();
969
970 if (Lexer.isNot(AsmToken::Identifier))
971 return TokError("unexpected symbol modifier following '@'");
972
973 MCSymbolRefExpr::VariantKind Variant =
974 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
975 if (Variant == MCSymbolRefExpr::VK_Invalid)
976 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
977
978 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
979 if (!ModifiedRes) {
980 return TokError("invalid modifier '" + getTok().getIdentifier() +
981 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000982 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000983
Daniel Dunbarcceba832010-09-17 02:47:07 +0000984 Res = ModifiedRes;
985 Lex();
986 }
987
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000988 // Try to constant fold it up front, if possible.
989 int64_t Value;
990 if (Res->EvaluateAsAbsolute(Value))
991 Res = MCConstantExpr::Create(Value, getContext());
992
993 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000994}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000995
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000996bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000997 Res = 0;
998 return ParseParenExpr(Res, EndLoc) ||
999 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +00001000}
1001
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001002bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001003 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001004
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001005 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001006 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +00001007 return true;
1008
Daniel Dunbare00b0112009-10-16 01:57:52 +00001009 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001010 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +00001011
1012 return false;
1013}
1014
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001015static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001016 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001017 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001018 default:
1019 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001020
Jim Grosbachfbe16812011-08-20 16:24:13 +00001021 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001022 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001023 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001024 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001025 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001026 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001027 return 1;
1028
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001029
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001030 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001031 //
1032 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001033 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001034 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001035 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001036 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001037 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001038 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001039 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001040 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001041 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001042
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001043 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001044 case AsmToken::EqualEqual:
1045 Kind = MCBinaryExpr::EQ;
1046 return 3;
1047 case AsmToken::ExclaimEqual:
1048 case AsmToken::LessGreater:
1049 Kind = MCBinaryExpr::NE;
1050 return 3;
1051 case AsmToken::Less:
1052 Kind = MCBinaryExpr::LT;
1053 return 3;
1054 case AsmToken::LessEqual:
1055 Kind = MCBinaryExpr::LTE;
1056 return 3;
1057 case AsmToken::Greater:
1058 Kind = MCBinaryExpr::GT;
1059 return 3;
1060 case AsmToken::GreaterEqual:
1061 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001062 return 3;
1063
Jim Grosbachfbe16812011-08-20 16:24:13 +00001064 // Intermediate Precedence: <<, >>
1065 case AsmToken::LessLess:
1066 Kind = MCBinaryExpr::Shl;
1067 return 4;
1068 case AsmToken::GreaterGreater:
1069 Kind = MCBinaryExpr::Shr;
1070 return 4;
1071
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001072 // High Intermediate Precedence: +, -
1073 case AsmToken::Plus:
1074 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001075 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001076 case AsmToken::Minus:
1077 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001078 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001079
Jim Grosbachfbe16812011-08-20 16:24:13 +00001080 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001081 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001082 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001083 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001084 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001085 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001086 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001087 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001088 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001089 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001090 }
1091}
1092
1093
1094/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1095/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001096bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1097 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001098 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001099 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001100 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001101
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001102 // If the next token is lower precedence than we are allowed to eat, return
1103 // successfully with what we ate already.
1104 if (TokPrec < Precedence)
1105 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001106
Sean Callanan79ed1a82010-01-19 20:22:31 +00001107 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001108
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001109 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001110 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001111 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001112
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001113 // If BinOp binds less tightly with RHS than the operator after RHS, let
1114 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001115 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001116 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001117 if (TokPrec < NextTokPrec) {
Kevin Enderby88535dd2013-05-07 21:40:58 +00001118 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001119 }
1120
Daniel Dunbar475839e2009-06-29 20:37:27 +00001121 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001122 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001123 }
1124}
1125
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001126/// ParseStatement:
1127/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001128/// ::= Label* Directive ...Operands... EndOfStatement
1129/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001130bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001131 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001132 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001133 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001134 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001135 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001136
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001137 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001138 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001139 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001140 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001141 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001142 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001143 if (Lexer.is(AsmToken::Hash))
1144 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001145
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001146 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001147 if (Lexer.is(AsmToken::Integer)) {
1148 LocalLabelVal = getTok().getIntVal();
1149 if (LocalLabelVal < 0) {
1150 if (!TheCondState.Ignore)
1151 return TokError("unexpected token at start of statement");
1152 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001153 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001154 IDVal = getTok().getString();
1155 Lex(); // Consume the integer token to be used as an identifier token.
1156 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001157 if (!TheCondState.Ignore)
1158 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001159 }
1160 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001161 } else if (Lexer.is(AsmToken::Dot)) {
1162 // Treat '.' as a valid identifier in this context.
1163 Lex();
1164 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001165 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001166 if (!TheCondState.Ignore)
1167 return TokError("unexpected token at start of statement");
1168 IDVal = "";
1169 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001170
Chris Lattner7834fac2010-04-17 18:14:27 +00001171 // Handle conditional assembly here before checking for skipping. We
1172 // have to do this so that .endif isn't skipped in a ".if 0" block for
1173 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001174 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001175 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001176 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001177 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1178 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001179 switch (DirKind) {
1180 default:
1181 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001182 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001183 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001184 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001185 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001186 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001187 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001188 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001189 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001190 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001191 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001192 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001193 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001194 case DK_IFNDEF:
1195 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001196 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001197 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001198 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001199 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001200 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001201 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001202 return ParseDirectiveEndIf(IDLoc);
1203 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001204
Eli Benderskyed5df012013-01-16 19:32:36 +00001205 // Ignore the statement if in the middle of inactive conditional
1206 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001207 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001208 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001209 return false;
1210 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001211
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001212 // FIXME: Recurse on local labels?
1213
1214 // See what kind of statement we have.
1215 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001216 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001217 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001218
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001219 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001220 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001221
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001222 // Diagnose attempt to use '.' as a label.
1223 if (IDVal == ".")
1224 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1225
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001226 // Diagnose attempt to use a variable as a label.
1227 //
1228 // FIXME: Diagnostics. Note the location of the definition as a label.
1229 // FIXME: This doesn't diagnose assignment to a symbol which has been
1230 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001231 MCSymbol *Sym;
1232 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001233 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001234 else
1235 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001236 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001237 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001238
Daniel Dunbar959fd882009-08-26 22:13:22 +00001239 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001240 if (!ParsingInlineAsm)
1241 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001242
Kevin Enderby94c2e852011-12-09 18:09:40 +00001243 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001244 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001245 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001246 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1247 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001248
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001249 // Consume any end of statement token, if present, to avoid spurious
1250 // AddBlankLine calls().
1251 if (Lexer.is(AsmToken::EndOfStatement)) {
1252 Lex();
1253 if (Lexer.is(AsmToken::Eof))
1254 return false;
1255 }
1256
Eli Friedman2128aae2012-10-22 23:58:19 +00001257 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001258 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001259
Daniel Dunbar3f872332009-07-28 16:08:33 +00001260 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001261 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001262 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001263
Nico Weber4c4c7322011-01-28 03:04:41 +00001264 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001265
1266 default: // Normal instruction or directive.
1267 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001268 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001269
1270 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001271 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001272 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1273 return HandleMacroEntry(M, IDLoc);
1274 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001275
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001276 // Otherwise, we have a normal instruction or directive.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001277
Eli Bendersky6ee13082013-01-15 22:59:42 +00001278 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001279 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001280 // There are several entities interested in parsing directives:
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001281 //
Eli Bendersky6ee13082013-01-15 22:59:42 +00001282 // 1. The target-specific assembly parser. Some directives are target
1283 // specific or may potentially behave differently on certain targets.
1284 // 2. Asm parser extensions. For example, platform-specific parsers
1285 // (like the ELF parser) register themselves as extensions.
1286 // 3. The generic directive parser implemented by this class. These are
1287 // all the directives that behave in a target and platform independent
1288 // manner, or at least have a default behavior that's shared between
1289 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001290
Eli Bendersky6ee13082013-01-15 22:59:42 +00001291 // First query the target-specific parser. It will return 'true' if it
1292 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001293 if (!getTargetParser().ParseDirective(ID))
1294 return false;
1295
Eli Bendersky6ee13082013-01-15 22:59:42 +00001296 // Next, check the extention directive map to see if any extension has
1297 // registered itself to parse this directive.
1298 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1299 ExtensionDirectiveMap.lookup(IDVal);
1300 if (Handler.first)
1301 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1302
1303 // Finally, if no one else is interested in this directive, it must be
1304 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 switch (DirKind) {
1306 default:
1307 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_SET:
1309 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_ASCIZ:
1316 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_SHORT:
1321 case DK_VALUE:
1322 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001324 case DK_LONG:
1325 case DK_INT:
1326 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_QUAD:
1329 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_SINGLE:
1332 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001333 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001334 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001335 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001336 case DK_ALIGN: {
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=*/1);
1339 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_ALIGN32: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001341 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1343 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001347 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001348 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001349 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001350 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001363 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_GLOBL:
1366 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001382 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001383 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001384 case DK_COMM:
1385 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001386 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001387 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001388 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001389 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001390 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001391 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001392 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001393 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001394 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001395 case DK_CODE16:
1396 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001397 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001398 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001399 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001400 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001401 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001402 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001403 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001404 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001405 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001406 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001407 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001408 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001409 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001410 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001411 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001412 case DK_SLEB128:
1413 return ParseDirectiveLEB128(true);
1414 case DK_ULEB128:
1415 return ParseDirectiveLEB128(false);
1416 case DK_SPACE:
1417 case DK_SKIP:
1418 return ParseDirectiveSpace(IDVal);
1419 case DK_FILE:
1420 return ParseDirectiveFile(IDLoc);
1421 case DK_LINE:
1422 return ParseDirectiveLine();
1423 case DK_LOC:
1424 return ParseDirectiveLoc();
1425 case DK_STABS:
1426 return ParseDirectiveStabs();
1427 case DK_CFI_SECTIONS:
1428 return ParseDirectiveCFISections();
1429 case DK_CFI_STARTPROC:
1430 return ParseDirectiveCFIStartProc();
1431 case DK_CFI_ENDPROC:
1432 return ParseDirectiveCFIEndProc();
1433 case DK_CFI_DEF_CFA:
1434 return ParseDirectiveCFIDefCfa(IDLoc);
1435 case DK_CFI_DEF_CFA_OFFSET:
1436 return ParseDirectiveCFIDefCfaOffset();
1437 case DK_CFI_ADJUST_CFA_OFFSET:
1438 return ParseDirectiveCFIAdjustCfaOffset();
1439 case DK_CFI_DEF_CFA_REGISTER:
1440 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1441 case DK_CFI_OFFSET:
1442 return ParseDirectiveCFIOffset(IDLoc);
1443 case DK_CFI_REL_OFFSET:
1444 return ParseDirectiveCFIRelOffset(IDLoc);
1445 case DK_CFI_PERSONALITY:
1446 return ParseDirectiveCFIPersonalityOrLsda(true);
1447 case DK_CFI_LSDA:
1448 return ParseDirectiveCFIPersonalityOrLsda(false);
1449 case DK_CFI_REMEMBER_STATE:
1450 return ParseDirectiveCFIRememberState();
1451 case DK_CFI_RESTORE_STATE:
1452 return ParseDirectiveCFIRestoreState();
1453 case DK_CFI_SAME_VALUE:
1454 return ParseDirectiveCFISameValue(IDLoc);
1455 case DK_CFI_RESTORE:
1456 return ParseDirectiveCFIRestore(IDLoc);
1457 case DK_CFI_ESCAPE:
1458 return ParseDirectiveCFIEscape();
1459 case DK_CFI_SIGNAL_FRAME:
1460 return ParseDirectiveCFISignalFrame();
1461 case DK_CFI_UNDEFINED:
1462 return ParseDirectiveCFIUndefined(IDLoc);
1463 case DK_CFI_REGISTER:
1464 return ParseDirectiveCFIRegister(IDLoc);
1465 case DK_MACROS_ON:
1466 case DK_MACROS_OFF:
1467 return ParseDirectiveMacrosOnOff(IDVal);
1468 case DK_MACRO:
1469 return ParseDirectiveMacro(IDLoc);
1470 case DK_ENDM:
1471 case DK_ENDMACRO:
1472 return ParseDirectiveEndMacro(IDVal);
1473 case DK_PURGEM:
1474 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001475 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001476
Jim Grosbach686c0182012-05-01 18:38:27 +00001477 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001478 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001479
Chad Rosier469b1442013-02-12 21:33:51 +00001480 // __asm _emit or __asm __emit
1481 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1482 IDVal == "_EMIT" || IDVal == "__EMIT"))
1483 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1484
1485 // __asm align
1486 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1487 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001488
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001489 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001490
Chris Lattnera7f13542010-05-19 23:34:33 +00001491 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001492 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001493 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001494 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001495 IDLoc,
1496 Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001497 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001498
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001499 // Dump the parsed representation, if requested.
1500 if (getShowParsedOperands()) {
1501 SmallString<256> Str;
1502 raw_svector_ostream OS(Str);
1503 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001504 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001505 if (i != 0)
1506 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001507 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001508 }
1509 OS << "]";
1510
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001511 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001512 }
1513
Kevin Enderby613b7572011-11-01 22:27:22 +00001514 // If we are generating dwarf for assembly source files and the current
1515 // section is the initial text section then generate a .loc directive for
1516 // the instruction.
1517 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001518 getContext().getGenDwarfSection() ==
1519 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001520
Eli Benderskyed5df012013-01-16 19:32:36 +00001521 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001522
Eli Benderskyed5df012013-01-16 19:32:36 +00001523 // If we previously parsed a cpp hash file line comment then make sure the
1524 // current Dwarf File is for the CppHashFilename if not then emit the
1525 // Dwarf File table for it and adjust the line number for the .loc.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001526 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001527 getContext().getMCDwarfFiles();
1528 if (CppHashFilename.size() != 0) {
1529 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001530 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001531 getStreamer().EmitDwarfFileDirective(
1532 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001533
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001534 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
Kevin Enderbya8959492013-06-21 20:51:39 +00001535 // cache with the different Loc from the call above we save the last
1536 // info we queried here with SrcMgr.FindLineNumber().
1537 unsigned CppHashLocLineNo;
1538 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1539 CppHashLocLineNo = LastQueryLine;
1540 else {
1541 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1542 LastQueryLine = CppHashLocLineNo;
1543 LastQueryIDLoc = CppHashLoc;
1544 LastQueryBuffer = CppHashBuf;
1545 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001546 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001547 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001548
Kevin Enderby613b7572011-11-01 22:27:22 +00001549 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001550 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001551 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001552 StringRef());
1553 }
1554
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001555 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001556 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001557 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001558 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1559 Info.ParsedOperands,
1560 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001561 ParsingInlineAsm);
1562 }
Chris Lattner98986712010-01-14 22:21:20 +00001563
Chris Lattnercbf8a982010-09-11 16:18:25 +00001564 // Don't skip the rest of the line, the instruction parser is responsible for
1565 // that.
1566 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001567}
Chris Lattner9a023f72009-06-24 04:43:34 +00001568
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001569/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1570/// since they may not be able to be tokenized to get to the end of line token.
1571void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001572 if (!Lexer.is(AsmToken::EndOfStatement))
1573 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001574 // Eat EOL.
1575 Lex();
1576}
1577
1578/// ParseCppHashLineFilenameComment as this:
1579/// ::= # number "filename"
1580/// or just as a full line comment if it doesn't have a number and a string.
1581bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1582 Lex(); // Eat the hash token.
1583
1584 if (getLexer().isNot(AsmToken::Integer)) {
1585 // Consume the line since in cases it is not a well-formed line directive,
1586 // as if were simply a full line comment.
1587 EatToEndOfLine();
1588 return false;
1589 }
1590
1591 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001592 Lex();
1593
1594 if (getLexer().isNot(AsmToken::String)) {
1595 EatToEndOfLine();
1596 return false;
1597 }
1598
1599 StringRef Filename = getTok().getString();
1600 // Get rid of the enclosing quotes.
1601 Filename = Filename.substr(1, Filename.size()-2);
1602
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001603 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1604 CppHashLoc = L;
1605 CppHashFilename = Filename;
1606 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001607 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001608
1609 // Ignore any trailing characters, they're just comment.
1610 EatToEndOfLine();
1611 return false;
1612}
1613
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001614/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001615/// for the Filename and LineNo if any in the diagnostic.
1616void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1617 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1618 raw_ostream &OS = errs();
1619
1620 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1621 const SMLoc &DiagLoc = Diag.getLoc();
1622 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1623 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1624
1625 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1626 // before printing the message.
1627 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001628 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001629 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1630 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1631 }
1632
Eric Christopher2318ba12012-12-18 00:30:54 +00001633 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001634 // manager changed or buffer changed (like in a nested include) then just
1635 // print the normal diagnostic using its Filename and LineNo.
1636 if (!Parser->CppHashLineNumber ||
1637 &DiagSrcMgr != &Parser->SrcMgr ||
1638 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001639 if (Parser->SavedDiagHandler)
1640 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1641 else
1642 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001643 return;
1644 }
1645
Eric Christopher2318ba12012-12-18 00:30:54 +00001646 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001647 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1648 // the diagnostic.
1649 const std::string Filename = Parser->CppHashFilename;
1650
1651 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1652 int CppHashLocLineNo =
1653 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1654 int LineNo = Parser->CppHashLineNumber - 1 +
1655 (DiagLocLineNo - CppHashLocLineNo);
1656
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001657 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1658 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001659 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001660 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001661
Benjamin Kramer04a04262011-10-16 10:48:29 +00001662 if (Parser->SavedDiagHandler)
1663 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1664 else
1665 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001666}
1667
Rafael Espindola799aacf2012-08-21 18:29:30 +00001668// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1669// difference being that that function accepts '@' as part of identifiers and
1670// we can't do that. AsmLexer.cpp should probably be changed to handle
1671// '@' as a special case when needed.
1672static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001673 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1674 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001675}
1676
Rafael Espindola761cb062012-06-03 23:57:14 +00001677bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001678 const MCAsmMacroParameters &Parameters,
1679 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001680 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001681 unsigned NParameters = Parameters.size();
1682 if (NParameters != 0 && NParameters != A.size())
1683 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001684
Preston Gurd7b6f2032012-09-19 20:36:12 +00001685 // A macro without parameters is handled differently on Darwin:
1686 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001687 while (!Body.empty()) {
1688 // Scan for the next substitution.
1689 std::size_t End = Body.size(), Pos = 0;
1690 for (; Pos != End; ++Pos) {
1691 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001692 if (!NParameters) {
1693 // This macro has no parameters, look for $0, $1, etc.
1694 if (Body[Pos] != '$' || Pos + 1 == End)
1695 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001696
Rafael Espindola65366442011-06-05 02:43:45 +00001697 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001698 if (Next == '$' || Next == 'n' ||
1699 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001700 break;
1701 } else {
1702 // This macro has parameters, look for \foo, \bar, etc.
1703 if (Body[Pos] == '\\' && Pos + 1 != End)
1704 break;
1705 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001706 }
1707
1708 // Add the prefix.
1709 OS << Body.slice(0, Pos);
1710
1711 // Check if we reached the end.
1712 if (Pos == End)
1713 break;
1714
Rafael Espindola65366442011-06-05 02:43:45 +00001715 if (!NParameters) {
1716 switch (Body[Pos+1]) {
1717 // $$ => $
1718 case '$':
1719 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001720 break;
1721
Rafael Espindola65366442011-06-05 02:43:45 +00001722 // $n => number of arguments
1723 case 'n':
1724 OS << A.size();
1725 break;
1726
1727 // $[0-9] => argument
1728 default: {
1729 // Missing arguments are ignored.
1730 unsigned Index = Body[Pos+1] - '0';
1731 if (Index >= A.size())
1732 break;
1733
1734 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001735 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001736 ie = A[Index].end(); it != ie; ++it)
1737 OS << it->getString();
1738 break;
1739 }
1740 }
1741 Pos += 2;
1742 } else {
1743 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001744 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001745 ++I;
1746
1747 const char *Begin = Body.data() + Pos +1;
1748 StringRef Argument(Begin, I - (Pos +1));
1749 unsigned Index = 0;
1750 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001751 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001752 break;
1753
Preston Gurd7b6f2032012-09-19 20:36:12 +00001754 if (Index == NParameters) {
1755 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1756 Pos += 3;
1757 else {
1758 OS << '\\' << Argument;
1759 Pos = I;
1760 }
1761 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001762 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001763 ie = A[Index].end(); it != ie; ++it)
1764 if (it->getKind() == AsmToken::String)
1765 OS << it->getStringContents();
1766 else
1767 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001768
Preston Gurd7b6f2032012-09-19 20:36:12 +00001769 Pos += 1 + Argument.size();
1770 }
Rafael Espindola65366442011-06-05 02:43:45 +00001771 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001772 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001773 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001774 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001775
Rafael Espindola65366442011-06-05 02:43:45 +00001776 return false;
1777}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001778
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001779MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001780 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001781 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001782 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1783 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001784{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001785}
1786
Preston Gurd7b6f2032012-09-19 20:36:12 +00001787static bool IsOperator(AsmToken::TokenKind kind)
1788{
1789 switch (kind)
1790 {
1791 default:
1792 return false;
1793 case AsmToken::Plus:
1794 case AsmToken::Minus:
1795 case AsmToken::Tilde:
1796 case AsmToken::Slash:
1797 case AsmToken::Star:
1798 case AsmToken::Dot:
1799 case AsmToken::Equal:
1800 case AsmToken::EqualEqual:
1801 case AsmToken::Pipe:
1802 case AsmToken::PipePipe:
1803 case AsmToken::Caret:
1804 case AsmToken::Amp:
1805 case AsmToken::AmpAmp:
1806 case AsmToken::Exclaim:
1807 case AsmToken::ExclaimEqual:
1808 case AsmToken::Percent:
1809 case AsmToken::Less:
1810 case AsmToken::LessEqual:
1811 case AsmToken::LessLess:
1812 case AsmToken::LessGreater:
1813 case AsmToken::Greater:
1814 case AsmToken::GreaterEqual:
1815 case AsmToken::GreaterGreater:
1816 return true;
1817 }
1818}
1819
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001820bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001821 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001822 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001823 unsigned AddTokens = 0;
1824
1825 // gas accepts arguments separated by whitespace, except on Darwin
1826 if (!IsDarwin)
1827 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001828
1829 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001830 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1831 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001832 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001833 }
1834
1835 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1836 // Spaces and commas cannot be mixed to delimit parameters
1837 if (ArgumentDelimiter == AsmToken::Eof)
1838 ArgumentDelimiter = AsmToken::Comma;
1839 else if (ArgumentDelimiter != AsmToken::Comma) {
1840 Lexer.setSkipSpace(true);
1841 return TokError("expected ' ' for macro argument separator");
1842 }
1843 break;
1844 }
1845
1846 if (Lexer.is(AsmToken::Space)) {
1847 Lex(); // Eat spaces
1848
1849 // Spaces can delimit parameters, but could also be part an expression.
1850 // If the token after a space is an operator, add the token and the next
1851 // one into this argument
1852 if (ArgumentDelimiter == AsmToken::Space ||
1853 ArgumentDelimiter == AsmToken::Eof) {
1854 if (IsOperator(Lexer.getKind())) {
1855 // Check to see whether the token is used as an operator,
1856 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001857 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001858 if (*NextChar == ' ')
1859 AddTokens = 2;
1860 }
1861
1862 if (!AddTokens && ParenLevel == 0) {
1863 if (ArgumentDelimiter == AsmToken::Eof &&
1864 !IsOperator(Lexer.getKind()))
1865 ArgumentDelimiter = AsmToken::Space;
1866 break;
1867 }
1868 }
1869 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001870
1871 // HandleMacroEntry relies on not advancing the lexer here
1872 // to be able to fill in the remaining default parameter values
1873 if (Lexer.is(AsmToken::EndOfStatement))
1874 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001875
1876 // Adjust the current parentheses level.
1877 if (Lexer.is(AsmToken::LParen))
1878 ++ParenLevel;
1879 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1880 --ParenLevel;
1881
1882 // Append the token to the current argument list.
1883 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001884 if (AddTokens)
1885 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001886 Lex();
1887 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001888
1889 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001890 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001891 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001892 return false;
1893}
1894
1895// Parse the macro instantiation arguments.
Vladimir Medic7b0a7962013-08-20 13:33:18 +00001896bool AsmParser::ParseMacroArguments(const MCAsmMacro *M,
1897 MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001898 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001899 // Argument delimiter is initially unknown. It will be set by
1900 // ParseMacroArgument()
1901 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001902
1903 // Parse two kinds of macro invocations:
1904 // - macros defined without any parameters accept an arbitrary number of them
1905 // - macros defined with parameters accept at most that many of them
1906 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1907 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001908 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001909
Preston Gurd7b6f2032012-09-19 20:36:12 +00001910 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001911 return true;
1912
Preston Gurd6c9176a2012-09-19 20:29:04 +00001913 if (!MA.empty() || !NParameters)
1914 A.push_back(MA);
1915 else if (NParameters) {
1916 if (!M->Parameters[Parameter].second.empty())
1917 A.push_back(M->Parameters[Parameter].second);
1918 }
Jim Grosbach97146442012-07-30 22:44:17 +00001919
Preston Gurd6c9176a2012-09-19 20:29:04 +00001920 // At the end of the statement, fill in remaining arguments that have
1921 // default values. If there aren't any, then the next argument is
1922 // required but missing
1923 if (Lexer.is(AsmToken::EndOfStatement)) {
1924 if (NParameters && Parameter < NParameters - 1) {
1925 if (M->Parameters[Parameter + 1].second.empty())
1926 return TokError("macro argument '" +
1927 Twine(M->Parameters[Parameter + 1].first) +
1928 "' is missing");
1929 else
1930 continue;
1931 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001932 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001933 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001934
1935 if (Lexer.is(AsmToken::Comma))
1936 Lex();
1937 }
1938 return TokError("Too many arguments");
1939}
1940
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001941const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1942 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1943 return (I == MacroMap.end()) ? NULL : I->getValue();
1944}
1945
1946void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1947 MacroMap[Name] = new MCAsmMacro(Macro);
1948}
1949
1950void AsmParser::UndefineMacro(StringRef Name) {
1951 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1952 if (I != MacroMap.end()) {
1953 delete I->getValue();
1954 MacroMap.erase(I);
1955 }
1956}
1957
1958bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001959 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1960 // this, although we should protect against infinite loops.
1961 if (ActiveMacros.size() == 20)
1962 return TokError("macros cannot be nested more than 20 levels deep");
1963
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001964 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001965 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001966 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001967
Jim Grosbach97146442012-07-30 22:44:17 +00001968 // Remove any trailing empty arguments. Do this after-the-fact as we have
1969 // to keep empty arguments in the middle of the list or positionality
1970 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001971 while (!A.empty() && A.back().empty())
1972 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001973
Rafael Espindola65366442011-06-05 02:43:45 +00001974 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1975 // to hold the macro body with substitutions.
1976 SmallString<256> Buf;
1977 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001978 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001979
Rafael Espindola8a403d32012-08-08 14:51:03 +00001980 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001981 return true;
1982
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001983 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001984 // instantiation.
1985 OS << ".endmacro\n";
1986
Rafael Espindola65366442011-06-05 02:43:45 +00001987 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001988 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001989
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001990 // Create the macro instantiation object and add to the current macro
1991 // instantiation stack.
1992 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001993 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001994 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001995 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001996 ActiveMacros.push_back(MI);
1997
1998 // Jump to the macro instantiation and prime the lexer.
1999 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2000 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2001 Lex();
2002
2003 return false;
2004}
2005
2006void AsmParser::HandleMacroExit() {
2007 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00002008 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002009 Lex();
2010
2011 // Pop the instantiation entry.
2012 delete ActiveMacros.back();
2013 ActiveMacros.pop_back();
2014}
2015
Rafael Espindolae71cc862012-01-28 05:57:00 +00002016static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002017 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00002018 case MCExpr::Binary: {
2019 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
2020 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002021 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00002022 case MCExpr::Target:
2023 case MCExpr::Constant:
2024 return false;
2025 case MCExpr::SymbolRef: {
2026 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002027 if (S.isVariable())
2028 return IsUsedIn(Sym, S.getVariableValue());
2029 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002030 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002031 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00002032 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002033 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002034
2035 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002036}
2037
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002038bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2039 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002040 // FIXME: Use better location, we should use proper tokens.
2041 SMLoc EqualLoc = Lexer.getLoc();
2042
Daniel Dunbar821e3332009-08-31 08:09:28 +00002043 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002044 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002045 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002046
Rafael Espindolae71cc862012-01-28 05:57:00 +00002047 // Note: we don't count b as used in "a = b". This is to allow
2048 // a = b
2049 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002050
Daniel Dunbar3f872332009-07-28 16:08:33 +00002051 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002052 return TokError("unexpected token in assignment");
2053
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002054 // Error on assignment to '.'.
2055 if (Name == ".") {
2056 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2057 "(use '.space' or '.org').)"));
2058 }
2059
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002060 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002061 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002062
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002063 // Validate that the LHS is allowed to be a variable (either it has not been
2064 // used as a symbol, or it is an absolute symbol).
2065 MCSymbol *Sym = getContext().LookupSymbol(Name);
2066 if (Sym) {
2067 // Diagnose assignment to a label.
2068 //
2069 // FIXME: Diagnostics. Note the location of the definition as a label.
2070 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002071 if (IsUsedIn(Sym, Value))
2072 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2073 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002074 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002075 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2076 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002077 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002078 return Error(EqualLoc, "redefinition of '" + Name + "'");
2079 else if (!Sym->isVariable())
2080 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002081 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002082 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2083 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002084
2085 // Don't count these checks as uses.
2086 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002087 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002088 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002089
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002090 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002091
2092 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002093 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002094 if (NoDeadStrip)
2095 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2096
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002097
2098 return false;
2099}
2100
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002101/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002102/// ::= identifier
2103/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002104bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002105 // The assembler has relaxed rules for accepting identifiers, in particular we
2106 // allow things like '.globl $foo', which would normally be separate
2107 // tokens. At this level, we have already lexed so we cannot (currently)
2108 // handle this as a context dependent token, instead we detect adjacent tokens
2109 // and return the combined identifier.
2110 if (Lexer.is(AsmToken::Dollar)) {
2111 SMLoc DollarLoc = getLexer().getLoc();
2112
2113 // Consume the dollar sign, and check for a following identifier.
2114 Lex();
2115 if (Lexer.isNot(AsmToken::Identifier))
2116 return true;
2117
2118 // We have a '$' followed by an identifier, make sure they are adjacent.
2119 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2120 return true;
2121
2122 // Construct the joined identifier and consume the token.
2123 Res = StringRef(DollarLoc.getPointer(),
2124 getTok().getIdentifier().size() + 1);
2125 Lex();
2126 return false;
2127 }
2128
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002129 if (Lexer.isNot(AsmToken::Identifier) &&
2130 Lexer.isNot(AsmToken::String))
2131 return true;
2132
Sean Callanan18b83232010-01-19 21:44:56 +00002133 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002134
Sean Callanan79ed1a82010-01-19 20:22:31 +00002135 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002136
2137 return false;
2138}
2139
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002140/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002141/// ::= .equ identifier ',' expression
2142/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002143/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002144bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002145 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002146
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002147 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002148 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002149
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002150 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002151 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002152 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002153
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002154 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002155}
2156
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002157bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002158 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002159
2160 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002161 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002162 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2163 if (Str[i] != '\\') {
2164 Data += Str[i];
2165 continue;
2166 }
2167
2168 // Recognize escaped characters. Note that this escape semantics currently
2169 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2170 ++i;
2171 if (i == e)
2172 return TokError("unexpected backslash at end of string");
2173
2174 // Recognize octal sequences.
2175 if ((unsigned) (Str[i] - '0') <= 7) {
2176 // Consume up to three octal characters.
2177 unsigned Value = Str[i] - '0';
2178
2179 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2180 ++i;
2181 Value = Value * 8 + (Str[i] - '0');
2182
2183 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2184 ++i;
2185 Value = Value * 8 + (Str[i] - '0');
2186 }
2187 }
2188
2189 if (Value > 255)
2190 return TokError("invalid octal escape sequence (out of range)");
2191
2192 Data += (unsigned char) Value;
2193 continue;
2194 }
2195
2196 // Otherwise recognize individual escapes.
2197 switch (Str[i]) {
2198 default:
2199 // Just reject invalid escape sequences for now.
2200 return TokError("invalid escape sequence (unrecognized character)");
2201
2202 case 'b': Data += '\b'; break;
2203 case 'f': Data += '\f'; break;
2204 case 'n': Data += '\n'; break;
2205 case 'r': Data += '\r'; break;
2206 case 't': Data += '\t'; break;
2207 case '"': Data += '"'; break;
2208 case '\\': Data += '\\'; break;
2209 }
2210 }
2211
2212 return false;
2213}
2214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002216/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2217bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002218 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002219 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002220
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002222 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002223 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002224
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002225 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002226 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002227 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002228
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002229 getStreamer().EmitBytes(Data);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 if (ZeroTerminated)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002231 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002232
Sean Callanan79ed1a82010-01-19 20:22:31 +00002233 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002234
2235 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236 break;
2237
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002238 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002239 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002240 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002241 }
2242 }
2243
Sean Callanan79ed1a82010-01-19 20:22:31 +00002244 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002245 return false;
2246}
2247
2248/// ParseDirectiveValue
2249/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2250bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002251 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002252 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002253
Daniel Dunbara0d14262009-06-24 23:30:00 +00002254 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002255 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002256 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002257 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002258 return true;
2259
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002260 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002261 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2262 assert(Size <= 8 && "Invalid size");
2263 uint64_t IntValue = MCE->getValue();
2264 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2265 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002266 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach254cf032011-06-29 16:05:14 +00002267 } else
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002268 getStreamer().EmitValue(Value, Size);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002270 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002271 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002272
Daniel Dunbara0d14262009-06-24 23:30:00 +00002273 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002274 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002275 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002276 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002277 }
2278 }
2279
Sean Callanan79ed1a82010-01-19 20:22:31 +00002280 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002281 return false;
2282}
2283
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002284/// ParseDirectiveRealValue
2285/// ::= (.single | .double) [ expression (, expression)* ]
2286bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2287 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002288 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002289
2290 for (;;) {
2291 // We don't truly support arithmetic on floating point expressions, so we
2292 // have to manually parse unary prefixes.
2293 bool IsNeg = false;
2294 if (getLexer().is(AsmToken::Minus)) {
2295 Lex();
2296 IsNeg = true;
2297 } else if (getLexer().is(AsmToken::Plus))
2298 Lex();
2299
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002300 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002301 getLexer().isNot(AsmToken::Real) &&
2302 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002303 return TokError("unexpected token in directive");
2304
2305 // Convert to an APFloat.
2306 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002307 StringRef IDVal = getTok().getString();
2308 if (getLexer().is(AsmToken::Identifier)) {
2309 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2310 Value = APFloat::getInf(Semantics);
2311 else if (!IDVal.compare_lower("nan"))
2312 Value = APFloat::getNaN(Semantics, false, ~0);
2313 else
2314 return TokError("invalid floating point literal");
2315 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002316 APFloat::opInvalidOp)
2317 return TokError("invalid floating point literal");
2318 if (IsNeg)
2319 Value.changeSign();
2320
2321 // Consume the numeric token.
2322 Lex();
2323
2324 // Emit the value as an integer.
2325 APInt AsInt = Value.bitcastToAPInt();
2326 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002327 AsInt.getBitWidth() / 8);
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002328
2329 if (getLexer().is(AsmToken::EndOfStatement))
2330 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002331
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002332 if (getLexer().isNot(AsmToken::Comma))
2333 return TokError("unexpected token in directive");
2334 Lex();
2335 }
2336 }
2337
2338 Lex();
2339 return false;
2340}
2341
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002342/// ParseDirectiveZero
2343/// ::= .zero expression
2344bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002345 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002346
2347 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002348 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002349 return true;
2350
Rafael Espindolae452b172010-10-05 19:42:57 +00002351 int64_t Val = 0;
2352 if (getLexer().is(AsmToken::Comma)) {
2353 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002354 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002355 return true;
2356 }
2357
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002358 if (getLexer().isNot(AsmToken::EndOfStatement))
2359 return TokError("unexpected token in '.zero' directive");
2360
2361 Lex();
2362
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002363 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002364
2365 return false;
2366}
2367
Daniel Dunbara0d14262009-06-24 23:30:00 +00002368/// ParseDirectiveFill
2369/// ::= .fill expression , expression , expression
2370bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002371 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002372
Daniel Dunbara0d14262009-06-24 23:30:00 +00002373 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002374 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002375 return true;
2376
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002377 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002378 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002379 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002380
Daniel Dunbara0d14262009-06-24 23:30:00 +00002381 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002382 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002383 return true;
2384
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002385 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002386 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002387 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002388
Daniel Dunbara0d14262009-06-24 23:30:00 +00002389 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002390 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002391 return true;
2392
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002393 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002394 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002395
Sean Callanan79ed1a82010-01-19 20:22:31 +00002396 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002397
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002398 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2399 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002400
2401 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002402 getStreamer().EmitIntValue(FillExpr, FillSize);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002403
2404 return false;
2405}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002406
2407/// ParseDirectiveOrg
2408/// ::= .org expression [ , expression ]
2409bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002410 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002411
Daniel Dunbar821e3332009-08-31 08:09:28 +00002412 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002413 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002414 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002415 return true;
2416
2417 // Parse optional fill expression.
2418 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002419 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2420 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002421 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002422 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002423
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002424 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002425 return true;
2426
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002427 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002428 return TokError("unexpected token in '.org' directive");
2429 }
2430
Sean Callanan79ed1a82010-01-19 20:22:31 +00002431 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002432
Jim Grosbachebd4c052012-01-27 00:37:08 +00002433 // Only limited forms of relocatable expressions are accepted here, it
2434 // has to be relative to the current section. The streamer will return
2435 // 'true' if the expression wasn't evaluatable.
2436 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2437 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002438
2439 return false;
2440}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002441
2442/// ParseDirectiveAlign
2443/// ::= {.align, ...} expression [ , expression [ , expression ]]
2444bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002445 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002446
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002447 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002449 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002450 return true;
2451
2452 SMLoc MaxBytesLoc;
2453 bool HasFillExpr = false;
2454 int64_t FillExpr = 0;
2455 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002456 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2457 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002459 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002460
2461 // The fill expression can be omitted while specifying a maximum number of
2462 // alignment bytes, e.g:
2463 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002464 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002465 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002466 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002467 return true;
2468 }
2469
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002470 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2471 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002472 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002473 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002474
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002475 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002476 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002477 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002478
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002479 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002480 return TokError("unexpected token in directive");
2481 }
2482 }
2483
Sean Callanan79ed1a82010-01-19 20:22:31 +00002484 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002485
Daniel Dunbar648ac512010-05-17 21:54:30 +00002486 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002487 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002488
2489 // Compute alignment in bytes.
2490 if (IsPow2) {
2491 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002492 if (Alignment >= 32) {
2493 Error(AlignmentLoc, "invalid alignment value");
2494 Alignment = 31;
2495 }
2496
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002497 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002498 } else {
2499 // Reject alignments that aren't a power of two, for gas compatibility.
2500 if (!isPowerOf2_64(Alignment))
2501 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002502 }
2503
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002504 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002505 if (MaxBytesLoc.isValid()) {
2506 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002507 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2508 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002509 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002510 }
2511
2512 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002513 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2514 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002515 MaxBytesToFill = 0;
2516 }
2517 }
2518
Daniel Dunbar648ac512010-05-17 21:54:30 +00002519 // Check whether we should use optimal code alignment for this .align
2520 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002521 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002522 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2523 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002524 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002525 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002526 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002527 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2528 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002529 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002530
2531 return false;
2532}
2533
Eli Bendersky6ee13082013-01-15 22:59:42 +00002534/// ParseDirectiveFile
2535/// ::= .file [number] filename
2536/// ::= .file number directory filename
2537bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2538 // FIXME: I'm not sure what this is.
2539 int64_t FileNumber = -1;
2540 SMLoc FileNumberLoc = getLexer().getLoc();
2541 if (getLexer().is(AsmToken::Integer)) {
2542 FileNumber = getTok().getIntVal();
2543 Lex();
2544
2545 if (FileNumber < 1)
2546 return TokError("file number less than one");
2547 }
2548
2549 if (getLexer().isNot(AsmToken::String))
2550 return TokError("unexpected token in '.file' directive");
2551
2552 // Usually the directory and filename together, otherwise just the directory.
2553 StringRef Path = getTok().getString();
2554 Path = Path.substr(1, Path.size()-2);
2555 Lex();
2556
2557 StringRef Directory;
2558 StringRef Filename;
2559 if (getLexer().is(AsmToken::String)) {
2560 if (FileNumber == -1)
2561 return TokError("explicit path specified, but no file number");
2562 Filename = getTok().getString();
2563 Filename = Filename.substr(1, Filename.size()-2);
2564 Directory = Path;
2565 Lex();
2566 } else {
2567 Filename = Path;
2568 }
2569
2570 if (getLexer().isNot(AsmToken::EndOfStatement))
2571 return TokError("unexpected token in '.file' directive");
2572
2573 if (FileNumber == -1)
2574 getStreamer().EmitFileDirective(Filename);
2575 else {
2576 if (getContext().getGenDwarfForAssembly() == true)
2577 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2578 "used to generate dwarf debug info for assembly code");
2579
2580 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2581 Error(FileNumberLoc, "file number already allocated");
2582 }
2583
2584 return false;
2585}
2586
2587/// ParseDirectiveLine
2588/// ::= .line [number]
2589bool AsmParser::ParseDirectiveLine() {
2590 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2591 if (getLexer().isNot(AsmToken::Integer))
2592 return TokError("unexpected token in '.line' directive");
2593
2594 int64_t LineNumber = getTok().getIntVal();
2595 (void) LineNumber;
2596 Lex();
2597
2598 // FIXME: Do something with the .line.
2599 }
2600
2601 if (getLexer().isNot(AsmToken::EndOfStatement))
2602 return TokError("unexpected token in '.line' directive");
2603
2604 return false;
2605}
2606
2607/// ParseDirectiveLoc
2608/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2609/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2610/// The first number is a file number, must have been previously assigned with
2611/// a .file directive, the second number is the line number and optionally the
2612/// third number is a column position (zero if not specified). The remaining
2613/// optional items are .loc sub-directives.
2614bool AsmParser::ParseDirectiveLoc() {
2615 if (getLexer().isNot(AsmToken::Integer))
2616 return TokError("unexpected token in '.loc' directive");
2617 int64_t FileNumber = getTok().getIntVal();
2618 if (FileNumber < 1)
2619 return TokError("file number less than one in '.loc' directive");
2620 if (!getContext().isValidDwarfFileNumber(FileNumber))
2621 return TokError("unassigned file number in '.loc' directive");
2622 Lex();
2623
2624 int64_t LineNumber = 0;
2625 if (getLexer().is(AsmToken::Integer)) {
2626 LineNumber = getTok().getIntVal();
2627 if (LineNumber < 1)
2628 return TokError("line number less than one in '.loc' directive");
2629 Lex();
2630 }
2631
2632 int64_t ColumnPos = 0;
2633 if (getLexer().is(AsmToken::Integer)) {
2634 ColumnPos = getTok().getIntVal();
2635 if (ColumnPos < 0)
2636 return TokError("column position less than zero in '.loc' directive");
2637 Lex();
2638 }
2639
2640 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2641 unsigned Isa = 0;
2642 int64_t Discriminator = 0;
2643 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2644 for (;;) {
2645 if (getLexer().is(AsmToken::EndOfStatement))
2646 break;
2647
2648 StringRef Name;
2649 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002650 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002651 return TokError("unexpected token in '.loc' directive");
2652
2653 if (Name == "basic_block")
2654 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2655 else if (Name == "prologue_end")
2656 Flags |= DWARF2_FLAG_PROLOGUE_END;
2657 else if (Name == "epilogue_begin")
2658 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2659 else if (Name == "is_stmt") {
2660 Loc = getTok().getLoc();
2661 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002662 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002663 return true;
2664 // The expression must be the constant 0 or 1.
2665 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2666 int Value = MCE->getValue();
2667 if (Value == 0)
2668 Flags &= ~DWARF2_FLAG_IS_STMT;
2669 else if (Value == 1)
2670 Flags |= DWARF2_FLAG_IS_STMT;
2671 else
2672 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002673 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002674 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2675 }
Craig Topperefa703d2013-04-22 04:22:40 +00002676 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002677 Loc = getTok().getLoc();
2678 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002679 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002680 return true;
2681 // The expression must be a constant greater or equal to 0.
2682 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2683 int Value = MCE->getValue();
2684 if (Value < 0)
2685 return Error(Loc, "isa number less than zero");
2686 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002687 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002688 return Error(Loc, "isa number not a constant value");
2689 }
Craig Topperefa703d2013-04-22 04:22:40 +00002690 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002691 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002692 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002693 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002694 return Error(Loc, "unknown sub-directive in '.loc' directive");
2695 }
2696
2697 if (getLexer().is(AsmToken::EndOfStatement))
2698 break;
2699 }
2700 }
2701
2702 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2703 Isa, Discriminator, StringRef());
2704
2705 return false;
2706}
2707
2708/// ParseDirectiveStabs
2709/// ::= .stabs string, number, number, number
2710bool AsmParser::ParseDirectiveStabs() {
2711 return TokError("unsupported directive '.stabs'");
2712}
2713
2714/// ParseDirectiveCFISections
2715/// ::= .cfi_sections section [, section]
2716bool AsmParser::ParseDirectiveCFISections() {
2717 StringRef Name;
2718 bool EH = false;
2719 bool Debug = false;
2720
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002721 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002722 return TokError("Expected an identifier");
2723
2724 if (Name == ".eh_frame")
2725 EH = true;
2726 else if (Name == ".debug_frame")
2727 Debug = true;
2728
2729 if (getLexer().is(AsmToken::Comma)) {
2730 Lex();
2731
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002732 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002733 return TokError("Expected an identifier");
2734
2735 if (Name == ".eh_frame")
2736 EH = true;
2737 else if (Name == ".debug_frame")
2738 Debug = true;
2739 }
2740
2741 getStreamer().EmitCFISections(EH, Debug);
2742 return false;
2743}
2744
2745/// ParseDirectiveCFIStartProc
2746/// ::= .cfi_startproc
2747bool AsmParser::ParseDirectiveCFIStartProc() {
2748 getStreamer().EmitCFIStartProc();
2749 return false;
2750}
2751
2752/// ParseDirectiveCFIEndProc
2753/// ::= .cfi_endproc
2754bool AsmParser::ParseDirectiveCFIEndProc() {
2755 getStreamer().EmitCFIEndProc();
2756 return false;
2757}
2758
2759/// ParseRegisterOrRegisterNumber - parse register name or number.
2760bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2761 SMLoc DirectiveLoc) {
2762 unsigned RegNo;
2763
2764 if (getLexer().isNot(AsmToken::Integer)) {
2765 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2766 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002767 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002768 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002769 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002770
2771 return false;
2772}
2773
2774/// ParseDirectiveCFIDefCfa
2775/// ::= .cfi_def_cfa register, offset
2776bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2777 int64_t Register = 0;
2778 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2779 return true;
2780
2781 if (getLexer().isNot(AsmToken::Comma))
2782 return TokError("unexpected token in directive");
2783 Lex();
2784
2785 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002786 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002787 return true;
2788
2789 getStreamer().EmitCFIDefCfa(Register, Offset);
2790 return false;
2791}
2792
2793/// ParseDirectiveCFIDefCfaOffset
2794/// ::= .cfi_def_cfa_offset offset
2795bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2796 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002797 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002798 return true;
2799
2800 getStreamer().EmitCFIDefCfaOffset(Offset);
2801 return false;
2802}
2803
2804/// ParseDirectiveCFIRegister
2805/// ::= .cfi_register register, register
2806bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2807 int64_t Register1 = 0;
2808 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2809 return true;
2810
2811 if (getLexer().isNot(AsmToken::Comma))
2812 return TokError("unexpected token in directive");
2813 Lex();
2814
2815 int64_t Register2 = 0;
2816 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2817 return true;
2818
2819 getStreamer().EmitCFIRegister(Register1, Register2);
2820 return false;
2821}
2822
2823/// ParseDirectiveCFIAdjustCfaOffset
2824/// ::= .cfi_adjust_cfa_offset adjustment
2825bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2826 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002827 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002828 return true;
2829
2830 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2831 return false;
2832}
2833
2834/// ParseDirectiveCFIDefCfaRegister
2835/// ::= .cfi_def_cfa_register register
2836bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2837 int64_t Register = 0;
2838 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2839 return true;
2840
2841 getStreamer().EmitCFIDefCfaRegister(Register);
2842 return false;
2843}
2844
2845/// ParseDirectiveCFIOffset
2846/// ::= .cfi_offset register, offset
2847bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2848 int64_t Register = 0;
2849 int64_t Offset = 0;
2850
2851 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2852 return true;
2853
2854 if (getLexer().isNot(AsmToken::Comma))
2855 return TokError("unexpected token in directive");
2856 Lex();
2857
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002858 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002859 return true;
2860
2861 getStreamer().EmitCFIOffset(Register, Offset);
2862 return false;
2863}
2864
2865/// ParseDirectiveCFIRelOffset
2866/// ::= .cfi_rel_offset register, offset
2867bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2868 int64_t Register = 0;
2869
2870 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2871 return true;
2872
2873 if (getLexer().isNot(AsmToken::Comma))
2874 return TokError("unexpected token in directive");
2875 Lex();
2876
2877 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002878 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002879 return true;
2880
2881 getStreamer().EmitCFIRelOffset(Register, Offset);
2882 return false;
2883}
2884
2885static bool isValidEncoding(int64_t Encoding) {
2886 if (Encoding & ~0xff)
2887 return false;
2888
2889 if (Encoding == dwarf::DW_EH_PE_omit)
2890 return true;
2891
2892 const unsigned Format = Encoding & 0xf;
2893 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2894 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2895 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2896 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2897 return false;
2898
2899 const unsigned Application = Encoding & 0x70;
2900 if (Application != dwarf::DW_EH_PE_absptr &&
2901 Application != dwarf::DW_EH_PE_pcrel)
2902 return false;
2903
2904 return true;
2905}
2906
2907/// ParseDirectiveCFIPersonalityOrLsda
2908/// IsPersonality true for cfi_personality, false for cfi_lsda
2909/// ::= .cfi_personality encoding, [symbol_name]
2910/// ::= .cfi_lsda encoding, [symbol_name]
2911bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2912 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002913 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002914 return true;
2915 if (Encoding == dwarf::DW_EH_PE_omit)
2916 return false;
2917
2918 if (!isValidEncoding(Encoding))
2919 return TokError("unsupported encoding.");
2920
2921 if (getLexer().isNot(AsmToken::Comma))
2922 return TokError("unexpected token in directive");
2923 Lex();
2924
2925 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002926 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002927 return TokError("expected identifier in directive");
2928
2929 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2930
2931 if (IsPersonality)
2932 getStreamer().EmitCFIPersonality(Sym, Encoding);
2933 else
2934 getStreamer().EmitCFILsda(Sym, Encoding);
2935 return false;
2936}
2937
2938/// ParseDirectiveCFIRememberState
2939/// ::= .cfi_remember_state
2940bool AsmParser::ParseDirectiveCFIRememberState() {
2941 getStreamer().EmitCFIRememberState();
2942 return false;
2943}
2944
2945/// ParseDirectiveCFIRestoreState
2946/// ::= .cfi_remember_state
2947bool AsmParser::ParseDirectiveCFIRestoreState() {
2948 getStreamer().EmitCFIRestoreState();
2949 return false;
2950}
2951
2952/// ParseDirectiveCFISameValue
2953/// ::= .cfi_same_value register
2954bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2955 int64_t Register = 0;
2956
2957 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2958 return true;
2959
2960 getStreamer().EmitCFISameValue(Register);
2961 return false;
2962}
2963
2964/// ParseDirectiveCFIRestore
2965/// ::= .cfi_restore register
2966bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2967 int64_t Register = 0;
2968 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2969 return true;
2970
2971 getStreamer().EmitCFIRestore(Register);
2972 return false;
2973}
2974
2975/// ParseDirectiveCFIEscape
2976/// ::= .cfi_escape expression[,...]
2977bool AsmParser::ParseDirectiveCFIEscape() {
2978 std::string Values;
2979 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002980 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002981 return true;
2982
2983 Values.push_back((uint8_t)CurrValue);
2984
2985 while (getLexer().is(AsmToken::Comma)) {
2986 Lex();
2987
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002988 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002989 return true;
2990
2991 Values.push_back((uint8_t)CurrValue);
2992 }
2993
2994 getStreamer().EmitCFIEscape(Values);
2995 return false;
2996}
2997
2998/// ParseDirectiveCFISignalFrame
2999/// ::= .cfi_signal_frame
3000bool AsmParser::ParseDirectiveCFISignalFrame() {
3001 if (getLexer().isNot(AsmToken::EndOfStatement))
3002 return Error(getLexer().getLoc(),
3003 "unexpected token in '.cfi_signal_frame'");
3004
3005 getStreamer().EmitCFISignalFrame();
3006 return false;
3007}
3008
3009/// ParseDirectiveCFIUndefined
3010/// ::= .cfi_undefined register
3011bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3012 int64_t Register = 0;
3013
3014 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3015 return true;
3016
3017 getStreamer().EmitCFIUndefined(Register);
3018 return false;
3019}
3020
3021/// ParseDirectiveMacrosOnOff
3022/// ::= .macros_on
3023/// ::= .macros_off
3024bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3025 if (getLexer().isNot(AsmToken::EndOfStatement))
3026 return Error(getLexer().getLoc(),
3027 "unexpected token in '" + Directive + "' directive");
3028
3029 SetMacrosEnabled(Directive == ".macros_on");
3030 return false;
3031}
3032
3033/// ParseDirectiveMacro
3034/// ::= .macro name [parameters]
3035bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3036 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003037 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003038 return TokError("expected identifier in '.macro' directive");
3039
3040 MCAsmMacroParameters Parameters;
3041 // Argument delimiter is initially unknown. It will be set by
3042 // ParseMacroArgument()
3043 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3044 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3045 for (;;) {
3046 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003047 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003048 return TokError("expected identifier in '.macro' directive");
3049
3050 if (getLexer().is(AsmToken::Equal)) {
3051 Lex();
3052 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3053 return true;
3054 }
3055
3056 Parameters.push_back(Parameter);
3057
3058 if (getLexer().is(AsmToken::Comma))
3059 Lex();
3060 else if (getLexer().is(AsmToken::EndOfStatement))
3061 break;
3062 }
3063 }
3064
3065 // Eat the end of statement.
3066 Lex();
3067
3068 AsmToken EndToken, StartToken = getTok();
3069
3070 // Lex the macro definition.
3071 for (;;) {
3072 // Check whether we have reached the end of the file.
3073 if (getLexer().is(AsmToken::Eof))
3074 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3075
3076 // Otherwise, check whether we have reach the .endmacro.
3077 if (getLexer().is(AsmToken::Identifier) &&
3078 (getTok().getIdentifier() == ".endm" ||
3079 getTok().getIdentifier() == ".endmacro")) {
3080 EndToken = getTok();
3081 Lex();
3082 if (getLexer().isNot(AsmToken::EndOfStatement))
3083 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3084 "' directive");
3085 break;
3086 }
3087
3088 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003089 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003090 }
3091
3092 if (LookupMacro(Name)) {
3093 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3094 }
3095
3096 const char *BodyStart = StartToken.getLoc().getPointer();
3097 const char *BodyEnd = EndToken.getLoc().getPointer();
3098 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003099 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003100 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3101 return false;
3102}
3103
Kevin Enderby221514e2013-01-22 21:44:53 +00003104/// CheckForBadMacro
3105///
3106/// With the support added for named parameters there may be code out there that
3107/// is transitioning from positional parameters. In versions of gas that did
3108/// not support named parameters they would be ignored on the macro defintion.
3109/// But to support both styles of parameters this is not possible so if a macro
3110/// defintion has named parameters but does not use them and has what appears
3111/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3112/// warning that the positional parameter found in body which have no effect.
3113/// Hoping the developer will either remove the named parameters from the macro
3114/// definiton so the positional parameters get used if that was what was
3115/// intended or change the macro to use the named parameters. It is possible
3116/// this warning will trigger when the none of the named parameters are used
3117/// and the strings like $1 are infact to simply to be passed trough unchanged.
3118void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3119 StringRef Body,
3120 MCAsmMacroParameters Parameters) {
3121 // If this macro is not defined with named parameters the warning we are
3122 // checking for here doesn't apply.
3123 unsigned NParameters = Parameters.size();
3124 if (NParameters == 0)
3125 return;
3126
3127 bool NamedParametersFound = false;
3128 bool PositionalParametersFound = false;
3129
3130 // Look at the body of the macro for use of both the named parameters and what
3131 // are likely to be positional parameters. This is what expandMacro() is
3132 // doing when it finds the parameters in the body.
3133 while (!Body.empty()) {
3134 // Scan for the next possible parameter.
3135 std::size_t End = Body.size(), Pos = 0;
3136 for (; Pos != End; ++Pos) {
3137 // Check for a substitution or escape.
3138 // This macro is defined with parameters, look for \foo, \bar, etc.
3139 if (Body[Pos] == '\\' && Pos + 1 != End)
3140 break;
3141
3142 // This macro should have parameters, but look for $0, $1, ..., $n too.
3143 if (Body[Pos] != '$' || Pos + 1 == End)
3144 continue;
3145 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003146 if (Next == '$' || Next == 'n' ||
3147 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003148 break;
3149 }
3150
3151 // Check if we reached the end.
3152 if (Pos == End)
3153 break;
3154
3155 if (Body[Pos] == '$') {
3156 switch (Body[Pos+1]) {
3157 // $$ => $
3158 case '$':
3159 break;
3160
3161 // $n => number of arguments
3162 case 'n':
3163 PositionalParametersFound = true;
3164 break;
3165
3166 // $[0-9] => argument
3167 default: {
3168 PositionalParametersFound = true;
3169 break;
3170 }
3171 }
3172 Pos += 2;
3173 } else {
3174 unsigned I = Pos + 1;
3175 while (isIdentifierChar(Body[I]) && I + 1 != End)
3176 ++I;
3177
3178 const char *Begin = Body.data() + Pos +1;
3179 StringRef Argument(Begin, I - (Pos +1));
3180 unsigned Index = 0;
3181 for (; Index < NParameters; ++Index)
3182 if (Parameters[Index].first == Argument)
3183 break;
3184
3185 if (Index == NParameters) {
3186 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3187 Pos += 3;
3188 else {
3189 Pos = I;
3190 }
3191 } else {
3192 NamedParametersFound = true;
3193 Pos += 1 + Argument.size();
3194 }
3195 }
3196 // Update the scan point.
3197 Body = Body.substr(Pos);
3198 }
3199
3200 if (!NamedParametersFound && PositionalParametersFound)
3201 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3202 "used in macro body, possible positional parameter "
3203 "found in body which will have no effect");
3204}
3205
Eli Bendersky6ee13082013-01-15 22:59:42 +00003206/// ParseDirectiveEndMacro
3207/// ::= .endm
3208/// ::= .endmacro
3209bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3210 if (getLexer().isNot(AsmToken::EndOfStatement))
3211 return TokError("unexpected token in '" + Directive + "' directive");
3212
3213 // If we are inside a macro instantiation, terminate the current
3214 // instantiation.
3215 if (InsideMacroInstantiation()) {
3216 HandleMacroExit();
3217 return false;
3218 }
3219
3220 // Otherwise, this .endmacro is a stray entry in the file; well formed
3221 // .endmacro directives are handled during the macro definition parsing.
3222 return TokError("unexpected '" + Directive + "' in file, "
3223 "no current macro definition");
3224}
3225
3226/// ParseDirectivePurgeMacro
3227/// ::= .purgem
3228bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3229 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003230 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003231 return TokError("expected identifier in '.purgem' directive");
3232
3233 if (getLexer().isNot(AsmToken::EndOfStatement))
3234 return TokError("unexpected token in '.purgem' directive");
3235
3236 if (!LookupMacro(Name))
3237 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3238
3239 UndefineMacro(Name);
3240 return false;
3241}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003242
3243/// ParseDirectiveBundleAlignMode
3244/// ::= {.bundle_align_mode} expression
3245bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003246 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003247
3248 // Expect a single argument: an expression that evaluates to a constant
3249 // in the inclusive range 0-30.
3250 SMLoc ExprLoc = getLexer().getLoc();
3251 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003252 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003253 return true;
3254 else if (getLexer().isNot(AsmToken::EndOfStatement))
3255 return TokError("unexpected token after expression in"
3256 " '.bundle_align_mode' directive");
3257 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3258 return Error(ExprLoc,
3259 "invalid bundle alignment size (expected between 0 and 30)");
3260
3261 Lex();
3262
3263 // Because of AlignSizePow2's verified range we can safely truncate it to
3264 // unsigned.
3265 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3266 return false;
3267}
3268
3269/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003270/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003271bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003272 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003273 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003274
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003275 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3276 StringRef Option;
3277 SMLoc Loc = getTok().getLoc();
3278 const char *kInvalidOptionError =
3279 "invalid option for '.bundle_lock' directive";
3280
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003281 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003282 return Error(Loc, kInvalidOptionError);
3283
3284 if (Option != "align_to_end")
3285 return Error(Loc, kInvalidOptionError);
3286 else if (getLexer().isNot(AsmToken::EndOfStatement))
3287 return Error(Loc,
3288 "unexpected token after '.bundle_lock' directive option");
3289 AlignToEnd = true;
3290 }
3291
Eli Bendersky4766ef42012-12-20 19:05:53 +00003292 Lex();
3293
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003294 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003295 return false;
3296}
3297
3298/// ParseDirectiveBundleLock
3299/// ::= {.bundle_lock}
3300bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003301 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003302
3303 if (getLexer().isNot(AsmToken::EndOfStatement))
3304 return TokError("unexpected token in '.bundle_unlock' directive");
3305 Lex();
3306
3307 getStreamer().EmitBundleUnlock();
3308 return false;
3309}
3310
Eli Bendersky6ee13082013-01-15 22:59:42 +00003311/// ParseDirectiveSpace
3312/// ::= (.skip | .space) expression [ , expression ]
3313bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003314 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003315
3316 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003317 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003318 return true;
3319
3320 int64_t FillExpr = 0;
3321 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3322 if (getLexer().isNot(AsmToken::Comma))
3323 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3324 Lex();
3325
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003326 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003327 return true;
3328
3329 if (getLexer().isNot(AsmToken::EndOfStatement))
3330 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3331 }
3332
3333 Lex();
3334
3335 if (NumBytes <= 0)
3336 return TokError("invalid number of bytes in '" +
3337 Twine(IDVal) + "' directive");
3338
3339 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00003340 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003341
3342 return false;
3343}
3344
3345/// ParseDirectiveLEB128
3346/// ::= (.sleb128 | .uleb128) expression
3347bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003348 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003349 const MCExpr *Value;
3350
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003351 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003352 return true;
3353
3354 if (getLexer().isNot(AsmToken::EndOfStatement))
3355 return TokError("unexpected token in directive");
3356
3357 if (Signed)
3358 getStreamer().EmitSLEB128Value(Value);
3359 else
3360 getStreamer().EmitULEB128Value(Value);
3361
3362 return false;
3363}
3364
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003365/// ParseDirectiveSymbolAttribute
3366/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003367bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003368 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003369 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003370 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003371 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003372
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003373 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003374 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003375
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003376 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003377
Jim Grosbach10ec6502011-09-15 17:56:49 +00003378 // Assembler local symbols don't make any sense here. Complain loudly.
3379 if (Sym->isTemporary())
3380 return Error(Loc, "non-local symbol required in directive");
3381
Saleem Abdulrasool1c9cd022013-08-09 01:52:03 +00003382 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3383 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003384
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003385 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003386 break;
3387
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003388 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003389 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003390 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003391 }
3392 }
3393
Sean Callanan79ed1a82010-01-19 20:22:31 +00003394 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003395 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003396}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003397
3398/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003399/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3400bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003401 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003402
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003403 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003404 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003405 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003406 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003407
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003408 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003409 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003410
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003411 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003412 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003413 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003414
3415 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003416 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003417 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003418 return true;
3419
3420 int64_t Pow2Alignment = 0;
3421 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003422 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003423 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003424 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003425 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003426 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003427
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003428 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3429 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003430 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3431
Chris Lattner258281d2010-01-19 06:22:22 +00003432 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003433 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3434 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003435 if (!isPowerOf2_64(Pow2Alignment))
3436 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3437 Pow2Alignment = Log2_64(Pow2Alignment);
3438 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003439 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003440
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003441 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003442 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003443
Sean Callanan79ed1a82010-01-19 20:22:31 +00003444 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003445
Chris Lattner1fc3d752009-07-09 17:25:12 +00003446 // NOTE: a size of zero for a .comm should create a undefined symbol
3447 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003448 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003449 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3450 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003451
Eric Christopherc260a3e2010-05-14 01:38:54 +00003452 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003453 // may internally end up wanting an alignment in bytes.
3454 // FIXME: Diagnose overflow.
3455 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003456 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3457 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003458
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003459 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003460 return Error(IDLoc, "invalid symbol redefinition");
3461
Chris Lattner1fc3d752009-07-09 17:25:12 +00003462 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003463 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003464 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003465 return false;
3466 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003467
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003468 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003469 return false;
3470}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003471
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003472/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003473/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003474bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003475 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003476 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003477
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003478 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003479 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003480 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003481
Sean Callanan79ed1a82010-01-19 20:22:31 +00003482 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003483
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003484 if (Str.empty())
3485 Error(Loc, ".abort detected. Assembly stopping.");
3486 else
3487 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003488 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003489
3490 return false;
3491}
Kevin Enderby71148242009-07-14 21:35:03 +00003492
Kevin Enderby1f049b22009-07-14 23:21:55 +00003493/// ParseDirectiveInclude
3494/// ::= .include "filename"
3495bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003496 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003497 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003498
Sean Callanan18b83232010-01-19 21:44:56 +00003499 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003500 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003501 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003502
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003503 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003504 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003505
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003506 // Strip the quotes.
3507 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003508
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003509 // Attempt to switch the lexer to the included file before consuming the end
3510 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003511 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003512 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003513 return true;
3514 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003515
3516 return false;
3517}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003518
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003519/// ParseDirectiveIncbin
3520/// ::= .incbin "filename"
3521bool AsmParser::ParseDirectiveIncbin() {
3522 if (getLexer().isNot(AsmToken::String))
3523 return TokError("expected string in '.incbin' directive");
3524
3525 std::string Filename = getTok().getString();
3526 SMLoc IncbinLoc = getLexer().getLoc();
3527 Lex();
3528
3529 if (getLexer().isNot(AsmToken::EndOfStatement))
3530 return TokError("unexpected token in '.incbin' directive");
3531
3532 // Strip the quotes.
3533 Filename = Filename.substr(1, Filename.size()-2);
3534
3535 // Attempt to process the included file.
3536 if (ProcessIncbinFile(Filename)) {
3537 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3538 return true;
3539 }
3540
3541 return false;
3542}
3543
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003544/// ParseDirectiveIf
3545/// ::= .if expression
3546bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003547 TheCondStack.push_back(TheCondState);
3548 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003549 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003550 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003551 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003552 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003553 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003554 return true;
3555
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003556 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003557 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003558
Sean Callanan79ed1a82010-01-19 20:22:31 +00003559 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003560
3561 TheCondState.CondMet = ExprValue;
3562 TheCondState.Ignore = !TheCondState.CondMet;
3563 }
3564
3565 return false;
3566}
3567
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003568/// ParseDirectiveIfb
3569/// ::= .ifb string
3570bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3571 TheCondStack.push_back(TheCondState);
3572 TheCondState.TheCond = AsmCond::IfCond;
3573
Benjamin Kramer29739e72012-05-12 16:52:21 +00003574 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003575 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003576 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003577 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003578
3579 if (getLexer().isNot(AsmToken::EndOfStatement))
3580 return TokError("unexpected token in '.ifb' directive");
3581
3582 Lex();
3583
3584 TheCondState.CondMet = ExpectBlank == Str.empty();
3585 TheCondState.Ignore = !TheCondState.CondMet;
3586 }
3587
3588 return false;
3589}
3590
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003591/// ParseDirectiveIfc
3592/// ::= .ifc string1, string2
3593bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3594 TheCondStack.push_back(TheCondState);
3595 TheCondState.TheCond = AsmCond::IfCond;
3596
Benjamin Kramer29739e72012-05-12 16:52:21 +00003597 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003598 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003599 } else {
3600 StringRef Str1 = ParseStringToComma();
3601
3602 if (getLexer().isNot(AsmToken::Comma))
3603 return TokError("unexpected token in '.ifc' directive");
3604
3605 Lex();
3606
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003607 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003608
3609 if (getLexer().isNot(AsmToken::EndOfStatement))
3610 return TokError("unexpected token in '.ifc' directive");
3611
3612 Lex();
3613
3614 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3615 TheCondState.Ignore = !TheCondState.CondMet;
3616 }
3617
3618 return false;
3619}
3620
3621/// ParseDirectiveIfdef
3622/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003623bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3624 StringRef Name;
3625 TheCondStack.push_back(TheCondState);
3626 TheCondState.TheCond = AsmCond::IfCond;
3627
3628 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003629 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003630 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003631 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003632 return TokError("expected identifier after '.ifdef'");
3633
3634 Lex();
3635
3636 MCSymbol *Sym = getContext().LookupSymbol(Name);
3637
3638 if (expect_defined)
3639 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3640 else
3641 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3642 TheCondState.Ignore = !TheCondState.CondMet;
3643 }
3644
3645 return false;
3646}
3647
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003648/// ParseDirectiveElseIf
3649/// ::= .elseif expression
3650bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3651 if (TheCondState.TheCond != AsmCond::IfCond &&
3652 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003653 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3654 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003655 TheCondState.TheCond = AsmCond::ElseIfCond;
3656
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003657 bool LastIgnoreState = false;
3658 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003659 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003660 if (LastIgnoreState || TheCondState.CondMet) {
3661 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003662 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003663 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003664 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003665 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003666 return true;
3667
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003668 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003669 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003670
Sean Callanan79ed1a82010-01-19 20:22:31 +00003671 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003672 TheCondState.CondMet = ExprValue;
3673 TheCondState.Ignore = !TheCondState.CondMet;
3674 }
3675
3676 return false;
3677}
3678
3679/// ParseDirectiveElse
3680/// ::= .else
3681bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003682 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003683 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003684
Sean Callanan79ed1a82010-01-19 20:22:31 +00003685 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003686
3687 if (TheCondState.TheCond != AsmCond::IfCond &&
3688 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003689 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3690 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003691 TheCondState.TheCond = AsmCond::ElseCond;
3692 bool LastIgnoreState = false;
3693 if (!TheCondStack.empty())
3694 LastIgnoreState = TheCondStack.back().Ignore;
3695 if (LastIgnoreState || TheCondState.CondMet)
3696 TheCondState.Ignore = true;
3697 else
3698 TheCondState.Ignore = false;
3699
3700 return false;
3701}
3702
3703/// ParseDirectiveEndIf
3704/// ::= .endif
3705bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003706 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003707 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003708
Sean Callanan79ed1a82010-01-19 20:22:31 +00003709 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003710
3711 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3712 TheCondStack.empty())
3713 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3714 ".else");
3715 if (!TheCondStack.empty()) {
3716 TheCondState = TheCondStack.back();
3717 TheCondStack.pop_back();
3718 }
3719
3720 return false;
3721}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003722
Eli Bendersky6ee13082013-01-15 22:59:42 +00003723void AsmParser::initializeDirectiveKindMap() {
3724 DirectiveKindMap[".set"] = DK_SET;
3725 DirectiveKindMap[".equ"] = DK_EQU;
3726 DirectiveKindMap[".equiv"] = DK_EQUIV;
3727 DirectiveKindMap[".ascii"] = DK_ASCII;
3728 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3729 DirectiveKindMap[".string"] = DK_STRING;
3730 DirectiveKindMap[".byte"] = DK_BYTE;
3731 DirectiveKindMap[".short"] = DK_SHORT;
3732 DirectiveKindMap[".value"] = DK_VALUE;
3733 DirectiveKindMap[".2byte"] = DK_2BYTE;
3734 DirectiveKindMap[".long"] = DK_LONG;
3735 DirectiveKindMap[".int"] = DK_INT;
3736 DirectiveKindMap[".4byte"] = DK_4BYTE;
3737 DirectiveKindMap[".quad"] = DK_QUAD;
3738 DirectiveKindMap[".8byte"] = DK_8BYTE;
3739 DirectiveKindMap[".single"] = DK_SINGLE;
3740 DirectiveKindMap[".float"] = DK_FLOAT;
3741 DirectiveKindMap[".double"] = DK_DOUBLE;
3742 DirectiveKindMap[".align"] = DK_ALIGN;
3743 DirectiveKindMap[".align32"] = DK_ALIGN32;
3744 DirectiveKindMap[".balign"] = DK_BALIGN;
3745 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3746 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3747 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3748 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3749 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3750 DirectiveKindMap[".org"] = DK_ORG;
3751 DirectiveKindMap[".fill"] = DK_FILL;
3752 DirectiveKindMap[".zero"] = DK_ZERO;
3753 DirectiveKindMap[".extern"] = DK_EXTERN;
3754 DirectiveKindMap[".globl"] = DK_GLOBL;
3755 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky6ee13082013-01-15 22:59:42 +00003756 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3757 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3758 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3759 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3760 DirectiveKindMap[".reference"] = DK_REFERENCE;
3761 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3762 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3763 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3764 DirectiveKindMap[".comm"] = DK_COMM;
3765 DirectiveKindMap[".common"] = DK_COMMON;
3766 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3767 DirectiveKindMap[".abort"] = DK_ABORT;
3768 DirectiveKindMap[".include"] = DK_INCLUDE;
3769 DirectiveKindMap[".incbin"] = DK_INCBIN;
3770 DirectiveKindMap[".code16"] = DK_CODE16;
3771 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3772 DirectiveKindMap[".rept"] = DK_REPT;
3773 DirectiveKindMap[".irp"] = DK_IRP;
3774 DirectiveKindMap[".irpc"] = DK_IRPC;
3775 DirectiveKindMap[".endr"] = DK_ENDR;
3776 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3777 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3778 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3779 DirectiveKindMap[".if"] = DK_IF;
3780 DirectiveKindMap[".ifb"] = DK_IFB;
3781 DirectiveKindMap[".ifnb"] = DK_IFNB;
3782 DirectiveKindMap[".ifc"] = DK_IFC;
3783 DirectiveKindMap[".ifnc"] = DK_IFNC;
3784 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3785 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3786 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3787 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3788 DirectiveKindMap[".else"] = DK_ELSE;
3789 DirectiveKindMap[".endif"] = DK_ENDIF;
3790 DirectiveKindMap[".skip"] = DK_SKIP;
3791 DirectiveKindMap[".space"] = DK_SPACE;
3792 DirectiveKindMap[".file"] = DK_FILE;
3793 DirectiveKindMap[".line"] = DK_LINE;
3794 DirectiveKindMap[".loc"] = DK_LOC;
3795 DirectiveKindMap[".stabs"] = DK_STABS;
3796 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3797 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3798 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3799 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3800 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3801 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3802 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3803 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3804 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3805 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3806 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3807 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3808 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3809 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3810 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3811 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3812 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3813 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3814 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3815 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3816 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3817 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3818 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3819 DirectiveKindMap[".macro"] = DK_MACRO;
3820 DirectiveKindMap[".endm"] = DK_ENDM;
3821 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3822 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003823}
3824
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003825
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003826MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003827 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003828
Rafael Espindola761cb062012-06-03 23:57:14 +00003829 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003830 for (;;) {
3831 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003832 if (getLexer().is(AsmToken::Eof)) {
3833 Error(DirectiveLoc, "no matching '.endr' in definition");
3834 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003835 }
3836
Rafael Espindola761cb062012-06-03 23:57:14 +00003837 if (Lexer.is(AsmToken::Identifier) &&
3838 (getTok().getIdentifier() == ".rept")) {
3839 ++NestLevel;
3840 }
3841
3842 // Otherwise, check whether we have reached the .endr.
3843 if (Lexer.is(AsmToken::Identifier) &&
3844 getTok().getIdentifier() == ".endr") {
3845 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003846 EndToken = getTok();
3847 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003848 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3849 TokError("unexpected token in '.endr' directive");
3850 return 0;
3851 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003852 break;
3853 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003854 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003855 }
3856
Rafael Espindola761cb062012-06-03 23:57:14 +00003857 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003858 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003859 }
3860
3861 const char *BodyStart = StartToken.getLoc().getPointer();
3862 const char *BodyEnd = EndToken.getLoc().getPointer();
3863 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3864
Rafael Espindola761cb062012-06-03 23:57:14 +00003865 // We Are Anonymous.
3866 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003867 MCAsmMacroParameters Parameters;
Benjamin Kramera2b0c332013-08-04 09:06:29 +00003868 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3869 return &MacroLikeBodies.back();
Rafael Espindola761cb062012-06-03 23:57:14 +00003870}
3871
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003872void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003873 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003874 OS << ".endr\n";
3875
3876 MemoryBuffer *Instantiation =
3877 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3878
Rafael Espindola761cb062012-06-03 23:57:14 +00003879 // Create the macro instantiation object and add to the current macro
3880 // instantiation stack.
3881 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003882 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003883 getTok().getLoc(),
3884 Instantiation);
3885 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003886
Rafael Espindola761cb062012-06-03 23:57:14 +00003887 // Jump to the macro instantiation and prime the lexer.
3888 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3889 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3890 Lex();
3891}
3892
3893bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3894 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003895 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003896 return TokError("unexpected token in '.rept' directive");
3897
3898 if (Count < 0)
3899 return TokError("Count is negative");
3900
3901 if (Lexer.isNot(AsmToken::EndOfStatement))
3902 return TokError("unexpected token in '.rept' directive");
3903
3904 // Eat the end of statement.
3905 Lex();
3906
3907 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003908 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003909 if (!M)
3910 return true;
3911
3912 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3913 // to hold the macro body with substitutions.
3914 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003915 MCAsmMacroParameters Parameters;
3916 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003917 raw_svector_ostream OS(Buf);
3918 while (Count--) {
3919 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3920 return true;
3921 }
3922 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003923
3924 return false;
3925}
3926
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003927/// ParseDirectiveIrp
3928/// ::= .irp symbol,values
3929bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003930 MCAsmMacroParameters Parameters;
3931 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003932
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003933 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003934 return TokError("expected identifier in '.irp' directive");
3935
3936 Parameters.push_back(Parameter);
3937
3938 if (Lexer.isNot(AsmToken::Comma))
3939 return TokError("expected comma in '.irp' directive");
3940
3941 Lex();
3942
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003943 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003944 if (ParseMacroArguments(0, A))
3945 return true;
3946
3947 // Eat the end of statement.
3948 Lex();
3949
3950 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003951 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003952 if (!M)
3953 return true;
3954
3955 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3956 // to hold the macro body with substitutions.
3957 SmallString<256> Buf;
3958 raw_svector_ostream OS(Buf);
3959
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003960 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3961 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003962 Args.push_back(*i);
3963
3964 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3965 return true;
3966 }
3967
3968 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3969
3970 return false;
3971}
3972
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003973/// ParseDirectiveIrpc
3974/// ::= .irpc symbol,values
3975bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003976 MCAsmMacroParameters Parameters;
3977 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003978
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003979 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003980 return TokError("expected identifier in '.irpc' directive");
3981
3982 Parameters.push_back(Parameter);
3983
3984 if (Lexer.isNot(AsmToken::Comma))
3985 return TokError("expected comma in '.irpc' directive");
3986
3987 Lex();
3988
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003989 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003990 if (ParseMacroArguments(0, A))
3991 return true;
3992
3993 if (A.size() != 1 || A.front().size() != 1)
3994 return TokError("unexpected token in '.irpc' directive");
3995
3996 // Eat the end of statement.
3997 Lex();
3998
3999 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004000 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004001 if (!M)
4002 return true;
4003
4004 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4005 // to hold the macro body with substitutions.
4006 SmallString<256> Buf;
4007 raw_svector_ostream OS(Buf);
4008
4009 StringRef Values = A.front().front().getString();
4010 std::size_t I, End = Values.size();
4011 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00004012 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004013 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
4014
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004015 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004016 Args.push_back(Arg);
4017
4018 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4019 return true;
4020 }
4021
4022 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
4023
4024 return false;
4025}
4026
Rafael Espindola761cb062012-06-03 23:57:14 +00004027bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4028 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004029 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004030
4031 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004032 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004033 assert(getLexer().is(AsmToken::EndOfStatement));
4034
Rafael Espindola761cb062012-06-03 23:57:14 +00004035 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004036 return false;
4037}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004038
Benjamin Kramer75234372013-02-15 20:37:21 +00004039bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4040 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004041 const MCExpr *Value;
4042 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004043 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004044 return true;
4045 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4046 if (!MCE)
4047 return Error(ExprLoc, "unexpected expression in _emit");
4048 uint64_t IntValue = MCE->getValue();
4049 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4050 return Error(ExprLoc, "literal value out of range for directive");
4051
Chad Rosier469b1442013-02-12 21:33:51 +00004052 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4053 return false;
4054}
4055
4056bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4057 const MCExpr *Value;
4058 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004059 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004060 return true;
4061 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4062 if (!MCE)
4063 return Error(ExprLoc, "unexpected expression in align");
4064 uint64_t IntValue = MCE->getValue();
4065 if (!isPowerOf2_64(IntValue))
4066 return Error(ExprLoc, "literal value not a power of two greater then zero");
4067
Benjamin Kramer75234372013-02-15 20:37:21 +00004068 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4069 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004070 return false;
4071}
4072
Chad Rosier19aa3e32013-02-13 21:27:17 +00004073// We are comparing pointers, but the pointers are relative to a single string.
4074// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004075static int RewritesSort(const void *A, const void *B) {
4076 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4077 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004078 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4079 return -1;
4080 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4081 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004082
Chad Rosier6b369ce2013-04-08 17:43:47 +00004083 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4084 // rewrite to the same location. Make sure the SizeDirective rewrite is
4085 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4086 // ensures the sort algorithm is stable.
4087 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4088 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004089 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004090
4091 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4092 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004093 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004094 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004095}
4096
Benjamin Kramer75234372013-02-15 20:37:21 +00004097bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004098AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004099 unsigned &NumOutputs, unsigned &NumInputs,
4100 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4101 SmallVectorImpl<std::string> &Constraints,
4102 SmallVectorImpl<std::string> &Clobbers,
4103 const MCInstrInfo *MII,
4104 const MCInstPrinter *IP,
4105 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004106 SmallVector<void *, 4> InputDecls;
4107 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004108 SmallVector<bool, 4> InputDeclsAddressOf;
4109 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004110 SmallVector<std::string, 4> InputConstraints;
4111 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004112 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004113
Benjamin Kramer75234372013-02-15 20:37:21 +00004114 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004115
4116 // Prime the lexer.
4117 Lex();
4118
4119 // While we have input, parse each statement.
4120 unsigned InputIdx = 0;
4121 unsigned OutputIdx = 0;
4122 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004123 ParseStatementInfo Info(&AsmStrRewrites);
4124 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004125 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004126
Chad Rosier57498012012-12-12 22:45:52 +00004127 if (Info.ParseError)
4128 return true;
4129
Benjamin Kramer75234372013-02-15 20:37:21 +00004130 if (Info.Opcode == ~0U)
4131 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004132
Benjamin Kramer75234372013-02-15 20:37:21 +00004133 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004134
Benjamin Kramer75234372013-02-15 20:37:21 +00004135 // Build the list of clobbers, outputs and inputs.
4136 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4137 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004138
Benjamin Kramer75234372013-02-15 20:37:21 +00004139 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004140 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004141 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004142
Benjamin Kramer75234372013-02-15 20:37:21 +00004143 // Register operand.
4144 if (Operand->isReg() && !Operand->needAddressOf()) {
4145 unsigned NumDefs = Desc.getNumDefs();
4146 // Clobber.
4147 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4148 ClobberRegs.push_back(Operand->getReg());
4149 continue;
4150 }
4151
4152 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004153 StringRef SymName = Operand->getSymName();
4154 if (SymName.empty())
4155 continue;
4156
Chad Rosier087c3092013-04-22 22:12:12 +00004157 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004158 if (!OpDecl)
4159 continue;
4160
4161 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004162 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004163 if (isOutput) {
4164 ++InputIdx;
4165 OutputDecls.push_back(OpDecl);
4166 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4167 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004168 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004169 } else {
4170 InputDecls.push_back(OpDecl);
4171 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4172 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004173 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004174 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004175 }
4176 }
4177
4178 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004179 NumOutputs = OutputDecls.size();
4180 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004181
4182 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004183 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4184 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4185 ClobberRegs.end());
4186 Clobbers.assign(ClobberRegs.size(), std::string());
4187 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4188 raw_string_ostream OS(Clobbers[I]);
4189 IP->printRegName(OS, ClobberRegs[I]);
4190 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004191
4192 // Merge the various outputs and inputs. Output are expected first.
4193 if (NumOutputs || NumInputs) {
4194 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004195 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004196 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004197 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004198 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004199 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004200 }
4201 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004202 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004203 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004204 }
4205 }
4206
4207 // Build the IR assembly string.
4208 std::string AsmStringIR;
4209 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004210 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4211 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004212 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4213 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4214 E = AsmStrRewrites.end();
4215 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004216 AsmRewriteKind Kind = (*I).Kind;
4217 if (Kind == AOK_Delete)
4218 continue;
4219
Chad Rosierb1f8c132012-10-18 15:49:34 +00004220 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004221 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004222
Chad Rosier023c8802013-03-19 17:32:17 +00004223 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004224 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004225 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004226 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004227
Chad Rosier5a719fc2012-10-23 17:43:43 +00004228 // Skip the original expression.
4229 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004230 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004231 continue;
4232 }
4233
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004234 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004235 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004236 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004237 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004238 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004239 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004240 break;
4241 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004242 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004243 break;
4244 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004245 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004246 break;
4247 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004248 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004249 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004250 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004251 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004252 default: break;
4253 case 8: OS << "byte ptr "; break;
4254 case 16: OS << "word ptr "; break;
4255 case 32: OS << "dword ptr "; break;
4256 case 64: OS << "qword ptr "; break;
4257 case 80: OS << "xword ptr "; break;
4258 case 128: OS << "xmmword ptr "; break;
4259 case 256: OS << "ymmword ptr "; break;
4260 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004261 break;
4262 case AOK_Emit:
4263 OS << ".byte";
4264 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004265 case AOK_Align: {
4266 unsigned Val = (*I).Val;
4267 OS << ".align " << Val;
4268
4269 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004270 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004271 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4272 break;
4273 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004274 case AOK_DotOperator:
4275 OS << (*I).Val;
4276 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004277 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004278
Chad Rosierb1f8c132012-10-18 15:49:34 +00004279 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004280 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004281 }
4282
4283 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004284 if (AsmStart != AsmEnd)
4285 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004286
4287 AsmString = OS.str();
4288 return false;
4289}
4290
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004291/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004292MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004293 MCContext &C, MCStreamer &Out,
4294 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004295 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004296}