blob: c50177cb0a41dbeff96cb61a702732cb16c7a3e6 [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
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000152 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000153 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000154
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000162 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000163
Devang Patel0db58bf2012-01-31 18:14:05 +0000164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
166
Preston Gurd7b6f2032012-09-19 20:36:12 +0000167 /// IsDarwin - is Darwin compatibility enabled?
168 bool IsDarwin;
169
Chad Rosier8f138d12012-10-15 17:19:13 +0000170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000171 bool ParsingInlineAsm;
172
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000173public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000176 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000180 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000181 ExtensionDirectiveHandler Handler) {
182 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183 }
184
185public:
186 /// @name MCAsmParser Interface
187 /// {
188
189 virtual SourceMgr &getSourceManager() { return SrcMgr; }
190 virtual MCAsmLexer &getLexer() { return Lexer; }
191 virtual MCContext &getContext() { return Ctx; }
192 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000193 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000194 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 else
197 return AssemblerDialect;
198 }
199 virtual void setAssemblerDialect(unsigned i) {
200 AssemblerDialect = i;
201 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000203 virtual bool Warning(SMLoc L, const Twine &Msg,
204 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
205 virtual bool Error(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000207
Craig Topper345d16d2012-08-29 05:48:09 +0000208 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Chad Rosier84125ca2012-10-13 00:26:04 +0000210 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000211 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000213 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000215 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000217 SmallVectorImpl<std::string> &Clobbers,
218 const MCInstrInfo *MII,
219 const MCInstPrinter *IP,
220 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000221
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000222 bool parseExpression(const MCExpr *&Res);
223 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
Chad Rosierba69b362013-04-10 17:35:30 +0000224 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000225 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000227
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000228 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000229 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000230 virtual bool parseIdentifier(StringRef &Res);
231 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000232
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000233 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234 /// }
235
236private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000237
Eli Friedman2128aae2012-10-22 23:58:19 +0000238 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000239 void EatToEndOfLine();
240 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000241
Kevin Enderby221514e2013-01-22 21:44:53 +0000242 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
243 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000244 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000245 const MCAsmMacroParameters &Parameters,
246 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000247 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000248
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000249 /// \brief Are macros enabled in the parser?
250 bool MacrosEnabled() {return MacrosEnabledFlag;}
251
252 /// \brief Control a flag in the parser that enables or disables macros.
253 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
254
255 /// \brief Lookup a previously defined macro.
256 /// \param Name Macro name.
257 /// \returns Pointer to macro. NULL if no such macro was defined.
258 const MCAsmMacro* LookupMacro(StringRef Name);
259
260 /// \brief Define a new macro with the given name and information.
261 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
262
263 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
264 void UndefineMacro(StringRef Name);
265
266 /// \brief Are we inside a macro instantiation?
267 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
268
269 /// \brief Handle entry to macro instantiation.
270 ///
271 /// \param M The macro.
272 /// \param NameLoc Instantiation location.
273 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
274
275 /// \brief Handle exit from macro instantiation.
276 void HandleMacroExit();
277
278 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
279 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
280 /// correct delimiter by the method.
281 bool ParseMacroArgument(MCAsmMacroArgument &MA,
282 AsmToken::TokenKind &ArgumentDelimiter);
283
284 /// \brief Parse all macro arguments for a given macro.
285 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
286
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000287 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000288 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000289 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
290 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000291 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000292 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000293
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000294 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
295 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000296 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
297 /// This returns true on failure.
298 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000299
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000300 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000301 /// current token is not set; clients should ensure Lex() is called
302 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000303 ///
304 /// \param InBuffer If not -1, should be the known buffer id that contains the
305 /// location.
306 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000307
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000308 /// \brief Parse up to the end of statement and a return the contents from the
309 /// current token until the end of the statement; the current token on exit
310 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000311 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000312
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000313 /// \brief Parse until the end of a statement or a comma is encountered,
314 /// return the contents from the current token up to the end or comma.
315 StringRef ParseStringToComma();
316
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000317 bool ParseAssignment(StringRef Name, bool allow_redef,
318 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000319
320 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
322 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000323 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324
Eli Bendersky6ee13082013-01-15 22:59:42 +0000325 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000326
Eli Bendersky6ee13082013-01-15 22:59:42 +0000327 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000328 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000329 DK_NO_DIRECTIVE, // Placeholder
330 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
331 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
332 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000333 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000334 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
335 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
336 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
337 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
338 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
339 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
340 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000341 DK_ELSEIF, DK_ELSE, DK_ENDIF,
342 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
343 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
344 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
345 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
346 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
347 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
348 DK_CFI_REGISTER,
349 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
350 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000351 };
352
Eli Bendersky6ee13082013-01-15 22:59:42 +0000353 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
354 /// directives parsed by this class.
355 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000356
357 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000358 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000359 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000360 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000361 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000362 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000363 // ".set", ".equ", ".equiv"
364 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000365 bool ParseDirectiveOrg(); // ".org"
366 // ".align{,32}", ".p2align{,w,l}"
367 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
368
Eli Bendersky6ee13082013-01-15 22:59:42 +0000369 // ".file", ".line", ".loc", ".stabs"
370 bool ParseDirectiveFile(SMLoc DirectiveLoc);
371 bool ParseDirectiveLine();
372 bool ParseDirectiveLoc();
373 bool ParseDirectiveStabs();
374
375 // .cfi directives
376 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
377 bool ParseDirectiveCFISections();
378 bool ParseDirectiveCFIStartProc();
379 bool ParseDirectiveCFIEndProc();
380 bool ParseDirectiveCFIDefCfaOffset();
381 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIAdjustCfaOffset();
383 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
387 bool ParseDirectiveCFIRememberState();
388 bool ParseDirectiveCFIRestoreState();
389 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIEscape();
392 bool ParseDirectiveCFISignalFrame();
393 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
394
395 // macro directives
396 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveEndMacro(StringRef Directive);
398 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
399 bool ParseDirectiveMacrosOnOff(StringRef Directive);
400
Eli Bendersky4766ef42012-12-20 19:05:53 +0000401 // ".bundle_align_mode"
402 bool ParseDirectiveBundleAlignMode();
403 // ".bundle_lock"
404 bool ParseDirectiveBundleLock();
405 // ".bundle_unlock"
406 bool ParseDirectiveBundleUnlock();
407
Eli Bendersky6ee13082013-01-15 22:59:42 +0000408 // ".space", ".skip"
409 bool ParseDirectiveSpace(StringRef IDVal);
410
411 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
412 bool ParseDirectiveLEB128(bool Signed);
413
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000414 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
415 /// accepts a single symbol (which should be a label or an external).
416 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000417
418 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
419
420 bool ParseDirectiveAbort(); // ".abort"
421 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000422 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000423
424 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000425 // ".ifb" or ".ifnb", depending on ExpectBlank.
426 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000427 // ".ifc" or ".ifnc", depending on ExpectEqual.
428 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000429 // ".ifdef" or ".ifndef", depending on expect_defined
430 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000431 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
432 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
433 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000434 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000435
436 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
437 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000438
Rafael Espindola761cb062012-06-03 23:57:14 +0000439 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000440 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
441 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000442 raw_svector_ostream &OS);
443 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000444 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000445 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000446 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000447
Chad Rosier469b1442013-02-12 21:33:51 +0000448 // "_emit" or "__emit"
449 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
450 size_t Len);
451
452 // "align"
453 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000454
Eli Bendersky6ee13082013-01-15 22:59:42 +0000455 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000456};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000457}
458
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459namespace llvm {
460
461extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000462extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000463extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000464
465}
466
Chris Lattneraaec2052010-01-19 19:46:13 +0000467enum { DEFAULT_ADDRSPACE = 0 };
468
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000469AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000470 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000471 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000472 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000473 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000474 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000475 // Save the old handler.
476 SavedDiagHandler = SrcMgr.getDiagHandler();
477 SavedDiagContext = SrcMgr.getDiagContext();
478 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000479 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000480 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000481
Daniel Dunbare4749702010-07-12 18:12:02 +0000482 // Initialize the platform / file format parser.
483 //
484 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
485 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000486 if (_MAI.hasMicrosoftFastStdCallMangling()) {
487 PlatformParser = createCOFFAsmParser();
488 PlatformParser->Initialize(*this);
489 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000490 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000491 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000492 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000493 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000494 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000495 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000496 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000497
Eli Bendersky6ee13082013-01-15 22:59:42 +0000498 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000499}
500
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000501AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000502 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
503
504 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000505 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000506 ie = MacroMap.end(); it != ie; ++it)
507 delete it->getValue();
508
Daniel Dunbare4749702010-07-12 18:12:02 +0000509 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000510}
511
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000512void AsmParser::PrintMacroInstantiations() {
513 // Print the active macro instantiation stack.
514 for (std::vector<MacroInstantiation*>::const_reverse_iterator
515 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000516 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
517 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000518}
519
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000520bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000521 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000522 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000523 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000525 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000526}
527
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000528bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000529 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000530 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000532 return true;
533}
534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000536 std::string IncludedFile;
537 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 if (NewBuf == -1)
539 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000544
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 return false;
546}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000547
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000548/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000549/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000550/// returns true on failure.
551bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
552 std::string IncludedFile;
553 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
554 if (NewBuf == -1)
555 return true;
556
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000557 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000558 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
559 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000560 return false;
561}
562
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000563void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
564 if (InBuffer != -1) {
565 CurBuffer = InBuffer;
566 } else {
567 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
568 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
570}
571
Sean Callananfd0b0282010-01-21 00:19:58 +0000572const AsmToken &AsmParser::Lex() {
573 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000574
Sean Callananfd0b0282010-01-21 00:19:58 +0000575 if (tok->is(AsmToken::Eof)) {
576 // If this is the end of an included file, pop the parent file off the
577 // include stack.
578 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
579 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000580 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000581 tok = &Lexer.Lex();
582 }
583 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000584
Sean Callananfd0b0282010-01-21 00:19:58 +0000585 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000586 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000589}
590
Chris Lattner79180e22010-04-05 23:15:42 +0000591bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000592 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000593 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000594 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000595
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000596 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000597 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000598
599 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000600 AsmCond StartingCondState = TheCondState;
601
Kevin Enderby613b7572011-11-01 22:27:22 +0000602 // If we are generating dwarf for assembly source files save the initial text
603 // section and generate a .file directive.
604 if (getContext().getGenDwarfForAssembly()) {
605 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000606 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
607 getStreamer().EmitLabel(SectionStartSym);
608 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000609 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000610 StringRef(),
611 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000612 }
613
Chris Lattnerb717fb02009-07-02 21:53:43 +0000614 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000615 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000616 ParseStatementInfo Info;
617 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000618
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000619 // We had an error, validate that one was emitted and recover by skipping to
620 // the next line.
621 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000622 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000623 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000624
625 if (TheCondState.TheCond != StartingCondState.TheCond ||
626 TheCondState.Ignore != StartingCondState.Ignore)
627 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000628
629 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000630 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000631 getContext().getMCDwarfFiles();
632 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000633 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000635 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000636
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000637 // Check to see that all assembler local symbols were actually defined.
638 // Targets that don't do subsections via symbols may not want this, though,
639 // so conservatively exclude them. Only do this if we're finalizing, though,
640 // as otherwise we won't necessarilly have seen everything yet.
641 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
642 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
643 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
644 e = Symbols.end();
645 i != e; ++i) {
646 MCSymbol *Sym = i->getValue();
647 // Variable symbols may not be marked as defined, so check those
648 // explicitly. If we know it's a variable, we have a definition for
649 // the purposes of this check.
650 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
651 // FIXME: We would really like to refer back to where the symbol was
652 // first referenced for a source location. We need to add something
653 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000654 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
655 "assembler local symbol '" + Sym->getName() +
656 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000657 }
658 }
659
660
Chris Lattner79180e22010-04-05 23:15:42 +0000661 // Finalize the output stream if there are no errors and if the client wants
662 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000663 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000664 Out.Finish();
665
Chris Lattnerb717fb02009-07-02 21:53:43 +0000666 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000667}
668
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000669void AsmParser::checkForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000670 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000671 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000672 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000673 }
674}
675
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000676/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
677void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000678 while (Lexer.isNot(AsmToken::EndOfStatement) &&
679 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000680 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000681
Chris Lattner2cf5f142009-06-22 01:29:09 +0000682 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000683 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000684 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000685}
686
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000687StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000688 const char *Start = getTok().getLoc().getPointer();
689
690 while (Lexer.isNot(AsmToken::EndOfStatement) &&
691 Lexer.isNot(AsmToken::Eof))
692 Lex();
693
694 const char *End = getTok().getLoc().getPointer();
695 return StringRef(Start, End - Start);
696}
Chris Lattnerc4193832009-06-22 05:51:26 +0000697
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000698StringRef AsmParser::ParseStringToComma() {
699 const char *Start = getTok().getLoc().getPointer();
700
701 while (Lexer.isNot(AsmToken::EndOfStatement) &&
702 Lexer.isNot(AsmToken::Comma) &&
703 Lexer.isNot(AsmToken::Eof))
704 Lex();
705
706 const char *End = getTok().getLoc().getPointer();
707 return StringRef(Start, End - Start);
708}
709
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710/// ParseParenExpr - Parse a paren expression and return it.
711/// NOTE: This assumes the leading '(' has already been consumed.
712///
713/// parenexpr ::= expr)
714///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000715bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000716 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000717 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000718 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000719 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000720 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000721 return false;
722}
Chris Lattnerc4193832009-06-22 05:51:26 +0000723
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000724/// ParseBracketExpr - Parse a bracket expression and return it.
725/// NOTE: This assumes the leading '[' has already been consumed.
726///
727/// bracketexpr ::= expr]
728///
729bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000730 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000731 if (Lexer.isNot(AsmToken::RBrac))
732 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000733 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000734 Lex();
735 return false;
736}
737
Chris Lattner74ec1a32009-06-22 06:32:03 +0000738/// ParsePrimaryExpr - Parse a primary expression and return it.
739/// primaryexpr ::= (parenexpr
740/// primaryexpr ::= symbol
741/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000742/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000743/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000744bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000745 SMLoc FirstTokenLoc = getLexer().getLoc();
746 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
747 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000748 default:
749 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000750 // If we have an error assume that we've already handled it.
751 case AsmToken::Error:
752 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000753 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000754 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000755 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000756 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000757 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000758 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000759 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000760 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000761 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000762 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000763 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000764 if (FirstTokenKind == AsmToken::Dollar)
765 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000766 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000767 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000768
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000769 EndLoc = SMLoc::getFromPointer(Identifier.end());
770
Daniel Dunbarfffff912009-10-16 01:34:54 +0000771 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000772 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000773 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000774
775 // Lookup the symbol variant if used.
776 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000777 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000779 if (Variant == MCSymbolRefExpr::VK_Invalid) {
780 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000781 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000782 }
783 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000784
Daniel Dunbarfffff912009-10-16 01:34:54 +0000785 // If this is an absolute variable reference, substitute it now to preserve
786 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000787 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000788 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000789 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000790
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000791 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000792 return false;
793 }
794
795 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000796 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000797 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000798 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000799 case AsmToken::Integer: {
800 SMLoc Loc = getTok().getLoc();
801 int64_t IntVal = getTok().getIntVal();
802 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000803 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000804 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000805 // Look for 'b' or 'f' following an Integer as a directional label
806 if (Lexer.getKind() == AsmToken::Identifier) {
807 StringRef IDVal = getTok().getString();
808 if (IDVal == "f" || IDVal == "b"){
809 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
810 IDVal == "f" ? 1 : 0);
811 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
812 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000813 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000814 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000815 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000816 Lex(); // Eat identifier.
817 }
818 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000819 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000820 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000821 case AsmToken::Real: {
822 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000823 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000824 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000825 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000826 Lex(); // Eat token.
827 return false;
828 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000829 case AsmToken::Dot: {
830 // This is a '.' reference, which references the current PC. Emit a
831 // temporary label to the streamer and refer to it.
832 MCSymbol *Sym = Ctx.CreateTempSymbol();
833 Out.EmitLabel(Sym);
834 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000835 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000836 Lex(); // Eat identifier.
837 return false;
838 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000839 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000840 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000841 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000842 case AsmToken::LBrac:
843 if (!PlatformParser->HasBracketExpressions())
844 return TokError("brackets expression not supported on this target");
845 Lex(); // Eat the '['.
846 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000847 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000848 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000849 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000851 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000853 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000854 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000855 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000857 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000858 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000859 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000860 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000861 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000863 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000864 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000865 }
866}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000867
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000868bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000869 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000870 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000871}
872
Chad Rosierba69b362013-04-10 17:35:30 +0000873bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
874 return ParsePrimaryExpr(Res, EndLoc);
875}
876
Daniel Dunbarcceba832010-09-17 02:47:07 +0000877const MCExpr *
878AsmParser::ApplyModifierToExpr(const MCExpr *E,
879 MCSymbolRefExpr::VariantKind Variant) {
880 // Recurse over the given expression, rebuilding it to apply the given variant
881 // if there is exactly one symbol.
882 switch (E->getKind()) {
883 case MCExpr::Target:
884 case MCExpr::Constant:
885 return 0;
886
887 case MCExpr::SymbolRef: {
888 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
889
890 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
891 TokError("invalid variant on expression '" +
892 getTok().getIdentifier() + "' (already modified)");
893 return E;
894 }
895
896 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
897 }
898
899 case MCExpr::Unary: {
900 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
901 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
902 if (!Sub)
903 return 0;
904 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
905 }
906
907 case MCExpr::Binary: {
908 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
909 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
910 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
911
912 if (!LHS && !RHS)
913 return 0;
914
915 if (!LHS) LHS = BE->getLHS();
916 if (!RHS) RHS = BE->getRHS();
917
918 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
919 }
920 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000921
Craig Topper85814382012-02-07 05:05:23 +0000922 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000923}
924
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000925/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000926///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000927/// expr ::= expr &&,|| expr -> lowest.
928/// expr ::= expr |,^,&,! expr
929/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
930/// expr ::= expr <<,>> expr
931/// expr ::= expr +,- expr
932/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000933/// expr ::= primaryexpr
934///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000935bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000936 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000937 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000938 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
939 return true;
940
Daniel Dunbarcceba832010-09-17 02:47:07 +0000941 // As a special case, we support 'a op b @ modifier' by rewriting the
942 // expression to include the modifier. This is inefficient, but in general we
943 // expect users to use 'a@modifier op b'.
944 if (Lexer.getKind() == AsmToken::At) {
945 Lex();
946
947 if (Lexer.isNot(AsmToken::Identifier))
948 return TokError("unexpected symbol modifier following '@'");
949
950 MCSymbolRefExpr::VariantKind Variant =
951 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
952 if (Variant == MCSymbolRefExpr::VK_Invalid)
953 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
954
955 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
956 if (!ModifiedRes) {
957 return TokError("invalid modifier '" + getTok().getIdentifier() +
958 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000959 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000960
Daniel Dunbarcceba832010-09-17 02:47:07 +0000961 Res = ModifiedRes;
962 Lex();
963 }
964
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000965 // Try to constant fold it up front, if possible.
966 int64_t Value;
967 if (Res->EvaluateAsAbsolute(Value))
968 Res = MCConstantExpr::Create(Value, getContext());
969
970 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000971}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000972
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000973bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000974 Res = 0;
975 return ParseParenExpr(Res, EndLoc) ||
976 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000977}
978
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000979bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000980 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000981
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000982 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000983 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000984 return true;
985
Daniel Dunbare00b0112009-10-16 01:57:52 +0000986 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000987 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000988
989 return false;
990}
991
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000992static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000993 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000994 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000995 default:
996 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000997
Jim Grosbachfbe16812011-08-20 16:24:13 +0000998 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000999 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001001 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001002 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001003 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001004 return 1;
1005
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001006
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001007 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001008 //
1009 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001012 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001013 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001014 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001015 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001016 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001017 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001018 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001019
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001020 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001021 case AsmToken::EqualEqual:
1022 Kind = MCBinaryExpr::EQ;
1023 return 3;
1024 case AsmToken::ExclaimEqual:
1025 case AsmToken::LessGreater:
1026 Kind = MCBinaryExpr::NE;
1027 return 3;
1028 case AsmToken::Less:
1029 Kind = MCBinaryExpr::LT;
1030 return 3;
1031 case AsmToken::LessEqual:
1032 Kind = MCBinaryExpr::LTE;
1033 return 3;
1034 case AsmToken::Greater:
1035 Kind = MCBinaryExpr::GT;
1036 return 3;
1037 case AsmToken::GreaterEqual:
1038 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001039 return 3;
1040
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 // Intermediate Precedence: <<, >>
1042 case AsmToken::LessLess:
1043 Kind = MCBinaryExpr::Shl;
1044 return 4;
1045 case AsmToken::GreaterGreater:
1046 Kind = MCBinaryExpr::Shr;
1047 return 4;
1048
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001049 // High Intermediate Precedence: +, -
1050 case AsmToken::Plus:
1051 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001053 case AsmToken::Minus:
1054 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001055 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001056
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001058 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001059 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001060 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001061 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001062 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001063 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001064 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001065 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001066 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001067 }
1068}
1069
1070
1071/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1072/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001073bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1074 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001075 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001076 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001077 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001078
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001079 // If the next token is lower precedence than we are allowed to eat, return
1080 // successfully with what we ate already.
1081 if (TokPrec < Precedence)
1082 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001083
Sean Callanan79ed1a82010-01-19 20:22:31 +00001084 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001085
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001087 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001088 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001089
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001090 // If BinOp binds less tightly with RHS than the operator after RHS, let
1091 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001092 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001093 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001094 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001095 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001096 }
1097
Daniel Dunbar475839e2009-06-29 20:37:27 +00001098 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001099 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001100 }
1101}
1102
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001103/// ParseStatement:
1104/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001105/// ::= Label* Directive ...Operands... EndOfStatement
1106/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001107bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001108 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001109 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001110 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001111 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001112 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001113
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001114 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001115 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001116 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001117 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001118 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001119 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001120 if (Lexer.is(AsmToken::Hash))
1121 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001122
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001123 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001124 if (Lexer.is(AsmToken::Integer)) {
1125 LocalLabelVal = getTok().getIntVal();
1126 if (LocalLabelVal < 0) {
1127 if (!TheCondState.Ignore)
1128 return TokError("unexpected token at start of statement");
1129 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001130 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001131 IDVal = getTok().getString();
1132 Lex(); // Consume the integer token to be used as an identifier token.
1133 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001136 }
1137 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001138 } else if (Lexer.is(AsmToken::Dot)) {
1139 // Treat '.' as a valid identifier in this context.
1140 Lex();
1141 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001142 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001143 if (!TheCondState.Ignore)
1144 return TokError("unexpected token at start of statement");
1145 IDVal = "";
1146 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001147
Chris Lattner7834fac2010-04-17 18:14:27 +00001148 // Handle conditional assembly here before checking for skipping. We
1149 // have to do this so that .endif isn't skipped in a ".if 0" block for
1150 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001152 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001153 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001154 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1155 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 switch (DirKind) {
1157 default:
1158 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001159 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001160 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001161 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001162 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001163 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001164 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001165 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001166 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001167 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001169 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001171 case DK_IFNDEF:
1172 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001173 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001174 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001175 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001176 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001177 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001178 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001179 return ParseDirectiveEndIf(IDLoc);
1180 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001181
Eli Benderskyed5df012013-01-16 19:32:36 +00001182 // Ignore the statement if in the middle of inactive conditional
1183 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001184 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001185 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001186 return false;
1187 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001188
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001189 // FIXME: Recurse on local labels?
1190
1191 // See what kind of statement we have.
1192 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001193 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001194 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001195
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001196 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001197 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001198
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001199 // Diagnose attempt to use '.' as a label.
1200 if (IDVal == ".")
1201 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1202
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001203 // Diagnose attempt to use a variable as a label.
1204 //
1205 // FIXME: Diagnostics. Note the location of the definition as a label.
1206 // FIXME: This doesn't diagnose assignment to a symbol which has been
1207 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001208 MCSymbol *Sym;
1209 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001210 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001211 else
1212 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001213 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001214 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001215
Daniel Dunbar959fd882009-08-26 22:13:22 +00001216 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001217 if (!ParsingInlineAsm)
1218 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001219
Kevin Enderby94c2e852011-12-09 18:09:40 +00001220 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001221 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001222 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001223 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1224 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001225
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001226 // Consume any end of statement token, if present, to avoid spurious
1227 // AddBlankLine calls().
1228 if (Lexer.is(AsmToken::EndOfStatement)) {
1229 Lex();
1230 if (Lexer.is(AsmToken::Eof))
1231 return false;
1232 }
1233
Eli Friedman2128aae2012-10-22 23:58:19 +00001234 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001235 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001236
Daniel Dunbar3f872332009-07-28 16:08:33 +00001237 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001238 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001239 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001240
Nico Weber4c4c7322011-01-28 03:04:41 +00001241 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001242
1243 default: // Normal instruction or directive.
1244 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001245 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001246
1247 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001248 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001249 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1250 return HandleMacroEntry(M, IDLoc);
1251 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001252
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001253 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001254
1255 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001256 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001257 // There are several entities interested in parsing directives:
1258 //
1259 // 1. The target-specific assembly parser. Some directives are target
1260 // specific or may potentially behave differently on certain targets.
1261 // 2. Asm parser extensions. For example, platform-specific parsers
1262 // (like the ELF parser) register themselves as extensions.
1263 // 3. The generic directive parser implemented by this class. These are
1264 // all the directives that behave in a target and platform independent
1265 // manner, or at least have a default behavior that's shared between
1266 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001267
Eli Bendersky6ee13082013-01-15 22:59:42 +00001268 // First query the target-specific parser. It will return 'true' if it
1269 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001270 if (!getTargetParser().ParseDirective(ID))
1271 return false;
1272
Eli Bendersky6ee13082013-01-15 22:59:42 +00001273 // Next, check the extention directive map to see if any extension has
1274 // registered itself to parse this directive.
1275 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1276 ExtensionDirectiveMap.lookup(IDVal);
1277 if (Handler.first)
1278 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1279
1280 // Finally, if no one else is interested in this directive, it must be
1281 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 switch (DirKind) {
1283 default:
1284 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_SET:
1286 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001287 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001288 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001289 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001290 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001291 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001292 case DK_ASCIZ:
1293 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001294 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001295 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001296 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001297 case DK_SHORT:
1298 case DK_VALUE:
1299 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_LONG:
1302 case DK_INT:
1303 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_QUAD:
1306 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_SINGLE:
1309 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1315 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1316 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1319 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1320 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001329 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001340 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_GLOBL:
1343 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001352 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001353 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001354 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001355 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001356 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001357 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001358 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001359 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_COMM:
1364 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001365 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001366 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_CODE16:
1375 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001379 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001380 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001381 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001382 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001383 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001384 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001385 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001386 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001387 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001388 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001389 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001390 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001391 case DK_SLEB128:
1392 return ParseDirectiveLEB128(true);
1393 case DK_ULEB128:
1394 return ParseDirectiveLEB128(false);
1395 case DK_SPACE:
1396 case DK_SKIP:
1397 return ParseDirectiveSpace(IDVal);
1398 case DK_FILE:
1399 return ParseDirectiveFile(IDLoc);
1400 case DK_LINE:
1401 return ParseDirectiveLine();
1402 case DK_LOC:
1403 return ParseDirectiveLoc();
1404 case DK_STABS:
1405 return ParseDirectiveStabs();
1406 case DK_CFI_SECTIONS:
1407 return ParseDirectiveCFISections();
1408 case DK_CFI_STARTPROC:
1409 return ParseDirectiveCFIStartProc();
1410 case DK_CFI_ENDPROC:
1411 return ParseDirectiveCFIEndProc();
1412 case DK_CFI_DEF_CFA:
1413 return ParseDirectiveCFIDefCfa(IDLoc);
1414 case DK_CFI_DEF_CFA_OFFSET:
1415 return ParseDirectiveCFIDefCfaOffset();
1416 case DK_CFI_ADJUST_CFA_OFFSET:
1417 return ParseDirectiveCFIAdjustCfaOffset();
1418 case DK_CFI_DEF_CFA_REGISTER:
1419 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1420 case DK_CFI_OFFSET:
1421 return ParseDirectiveCFIOffset(IDLoc);
1422 case DK_CFI_REL_OFFSET:
1423 return ParseDirectiveCFIRelOffset(IDLoc);
1424 case DK_CFI_PERSONALITY:
1425 return ParseDirectiveCFIPersonalityOrLsda(true);
1426 case DK_CFI_LSDA:
1427 return ParseDirectiveCFIPersonalityOrLsda(false);
1428 case DK_CFI_REMEMBER_STATE:
1429 return ParseDirectiveCFIRememberState();
1430 case DK_CFI_RESTORE_STATE:
1431 return ParseDirectiveCFIRestoreState();
1432 case DK_CFI_SAME_VALUE:
1433 return ParseDirectiveCFISameValue(IDLoc);
1434 case DK_CFI_RESTORE:
1435 return ParseDirectiveCFIRestore(IDLoc);
1436 case DK_CFI_ESCAPE:
1437 return ParseDirectiveCFIEscape();
1438 case DK_CFI_SIGNAL_FRAME:
1439 return ParseDirectiveCFISignalFrame();
1440 case DK_CFI_UNDEFINED:
1441 return ParseDirectiveCFIUndefined(IDLoc);
1442 case DK_CFI_REGISTER:
1443 return ParseDirectiveCFIRegister(IDLoc);
1444 case DK_MACROS_ON:
1445 case DK_MACROS_OFF:
1446 return ParseDirectiveMacrosOnOff(IDVal);
1447 case DK_MACRO:
1448 return ParseDirectiveMacro(IDLoc);
1449 case DK_ENDM:
1450 case DK_ENDMACRO:
1451 return ParseDirectiveEndMacro(IDVal);
1452 case DK_PURGEM:
1453 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001454 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001455
Jim Grosbach686c0182012-05-01 18:38:27 +00001456 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001457 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001458
Chad Rosier469b1442013-02-12 21:33:51 +00001459 // __asm _emit or __asm __emit
1460 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1461 IDVal == "_EMIT" || IDVal == "__EMIT"))
1462 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1463
1464 // __asm align
1465 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1466 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001467
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001468 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001469
Chris Lattnera7f13542010-05-19 23:34:33 +00001470 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001471 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001472 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001473 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1474 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001475 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001476
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001477 // Dump the parsed representation, if requested.
1478 if (getShowParsedOperands()) {
1479 SmallString<256> Str;
1480 raw_svector_ostream OS(Str);
1481 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001482 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001483 if (i != 0)
1484 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001485 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001486 }
1487 OS << "]";
1488
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001489 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001490 }
1491
Kevin Enderby613b7572011-11-01 22:27:22 +00001492 // If we are generating dwarf for assembly source files and the current
1493 // section is the initial text section then generate a .loc directive for
1494 // the instruction.
1495 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001496 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001497
Eli Benderskyed5df012013-01-16 19:32:36 +00001498 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001499
Eli Benderskyed5df012013-01-16 19:32:36 +00001500 // If we previously parsed a cpp hash file line comment then make sure the
1501 // current Dwarf File is for the CppHashFilename if not then emit the
1502 // Dwarf File table for it and adjust the line number for the .loc.
Manman Ren9e999ad2013-03-12 20:17:00 +00001503 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001504 getContext().getMCDwarfFiles();
1505 if (CppHashFilename.size() != 0) {
1506 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001507 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001508 getStreamer().EmitDwarfFileDirective(
1509 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001510
Kevin Enderby32c1a822012-11-05 21:55:41 +00001511 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001512 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001513 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001514
Kevin Enderby613b7572011-11-01 22:27:22 +00001515 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001516 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001517 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001518 StringRef());
1519 }
1520
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001521 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001522 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001523 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001524 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1525 Info.ParsedOperands,
1526 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001527 ParsingInlineAsm);
1528 }
Chris Lattner98986712010-01-14 22:21:20 +00001529
Chris Lattnercbf8a982010-09-11 16:18:25 +00001530 // Don't skip the rest of the line, the instruction parser is responsible for
1531 // that.
1532 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001533}
Chris Lattner9a023f72009-06-24 04:43:34 +00001534
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001535/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1536/// since they may not be able to be tokenized to get to the end of line token.
1537void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001538 if (!Lexer.is(AsmToken::EndOfStatement))
1539 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001540 // Eat EOL.
1541 Lex();
1542}
1543
1544/// ParseCppHashLineFilenameComment as this:
1545/// ::= # number "filename"
1546/// or just as a full line comment if it doesn't have a number and a string.
1547bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1548 Lex(); // Eat the hash token.
1549
1550 if (getLexer().isNot(AsmToken::Integer)) {
1551 // Consume the line since in cases it is not a well-formed line directive,
1552 // as if were simply a full line comment.
1553 EatToEndOfLine();
1554 return false;
1555 }
1556
1557 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001558 Lex();
1559
1560 if (getLexer().isNot(AsmToken::String)) {
1561 EatToEndOfLine();
1562 return false;
1563 }
1564
1565 StringRef Filename = getTok().getString();
1566 // Get rid of the enclosing quotes.
1567 Filename = Filename.substr(1, Filename.size()-2);
1568
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001569 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1570 CppHashLoc = L;
1571 CppHashFilename = Filename;
1572 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001573 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001574
1575 // Ignore any trailing characters, they're just comment.
1576 EatToEndOfLine();
1577 return false;
1578}
1579
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001580/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001581/// for the Filename and LineNo if any in the diagnostic.
1582void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1583 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1584 raw_ostream &OS = errs();
1585
1586 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1587 const SMLoc &DiagLoc = Diag.getLoc();
1588 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1589 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1590
1591 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1592 // before printing the message.
1593 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001594 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001595 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1596 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1597 }
1598
Eric Christopher2318ba12012-12-18 00:30:54 +00001599 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001600 // manager changed or buffer changed (like in a nested include) then just
1601 // print the normal diagnostic using its Filename and LineNo.
1602 if (!Parser->CppHashLineNumber ||
1603 &DiagSrcMgr != &Parser->SrcMgr ||
1604 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001605 if (Parser->SavedDiagHandler)
1606 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1607 else
1608 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001609 return;
1610 }
1611
Eric Christopher2318ba12012-12-18 00:30:54 +00001612 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001613 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1614 // the diagnostic.
1615 const std::string Filename = Parser->CppHashFilename;
1616
1617 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1618 int CppHashLocLineNo =
1619 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1620 int LineNo = Parser->CppHashLineNumber - 1 +
1621 (DiagLocLineNo - CppHashLocLineNo);
1622
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001623 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1624 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001625 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001626 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001627
Benjamin Kramer04a04262011-10-16 10:48:29 +00001628 if (Parser->SavedDiagHandler)
1629 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1630 else
1631 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001632}
1633
Rafael Espindola799aacf2012-08-21 18:29:30 +00001634// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1635// difference being that that function accepts '@' as part of identifiers and
1636// we can't do that. AsmLexer.cpp should probably be changed to handle
1637// '@' as a special case when needed.
1638static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001639 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1640 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001641}
1642
Rafael Espindola761cb062012-06-03 23:57:14 +00001643bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001644 const MCAsmMacroParameters &Parameters,
1645 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001646 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001647 unsigned NParameters = Parameters.size();
1648 if (NParameters != 0 && NParameters != A.size())
1649 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001650
Preston Gurd7b6f2032012-09-19 20:36:12 +00001651 // A macro without parameters is handled differently on Darwin:
1652 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001653 while (!Body.empty()) {
1654 // Scan for the next substitution.
1655 std::size_t End = Body.size(), Pos = 0;
1656 for (; Pos != End; ++Pos) {
1657 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001658 if (!NParameters) {
1659 // This macro has no parameters, look for $0, $1, etc.
1660 if (Body[Pos] != '$' || Pos + 1 == End)
1661 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001662
Rafael Espindola65366442011-06-05 02:43:45 +00001663 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001664 if (Next == '$' || Next == 'n' ||
1665 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001666 break;
1667 } else {
1668 // This macro has parameters, look for \foo, \bar, etc.
1669 if (Body[Pos] == '\\' && Pos + 1 != End)
1670 break;
1671 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001672 }
1673
1674 // Add the prefix.
1675 OS << Body.slice(0, Pos);
1676
1677 // Check if we reached the end.
1678 if (Pos == End)
1679 break;
1680
Rafael Espindola65366442011-06-05 02:43:45 +00001681 if (!NParameters) {
1682 switch (Body[Pos+1]) {
1683 // $$ => $
1684 case '$':
1685 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001686 break;
1687
Rafael Espindola65366442011-06-05 02:43:45 +00001688 // $n => number of arguments
1689 case 'n':
1690 OS << A.size();
1691 break;
1692
1693 // $[0-9] => argument
1694 default: {
1695 // Missing arguments are ignored.
1696 unsigned Index = Body[Pos+1] - '0';
1697 if (Index >= A.size())
1698 break;
1699
1700 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001701 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001702 ie = A[Index].end(); it != ie; ++it)
1703 OS << it->getString();
1704 break;
1705 }
1706 }
1707 Pos += 2;
1708 } else {
1709 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001710 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001711 ++I;
1712
1713 const char *Begin = Body.data() + Pos +1;
1714 StringRef Argument(Begin, I - (Pos +1));
1715 unsigned Index = 0;
1716 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001717 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001718 break;
1719
Preston Gurd7b6f2032012-09-19 20:36:12 +00001720 if (Index == NParameters) {
1721 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1722 Pos += 3;
1723 else {
1724 OS << '\\' << Argument;
1725 Pos = I;
1726 }
1727 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001728 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001729 ie = A[Index].end(); it != ie; ++it)
1730 if (it->getKind() == AsmToken::String)
1731 OS << it->getStringContents();
1732 else
1733 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001734
Preston Gurd7b6f2032012-09-19 20:36:12 +00001735 Pos += 1 + Argument.size();
1736 }
Rafael Espindola65366442011-06-05 02:43:45 +00001737 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001738 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001739 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001740 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001741
Rafael Espindola65366442011-06-05 02:43:45 +00001742 return false;
1743}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001744
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001745MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001746 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001747 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001748 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1749 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001750{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001751}
1752
Preston Gurd7b6f2032012-09-19 20:36:12 +00001753static bool IsOperator(AsmToken::TokenKind kind)
1754{
1755 switch (kind)
1756 {
1757 default:
1758 return false;
1759 case AsmToken::Plus:
1760 case AsmToken::Minus:
1761 case AsmToken::Tilde:
1762 case AsmToken::Slash:
1763 case AsmToken::Star:
1764 case AsmToken::Dot:
1765 case AsmToken::Equal:
1766 case AsmToken::EqualEqual:
1767 case AsmToken::Pipe:
1768 case AsmToken::PipePipe:
1769 case AsmToken::Caret:
1770 case AsmToken::Amp:
1771 case AsmToken::AmpAmp:
1772 case AsmToken::Exclaim:
1773 case AsmToken::ExclaimEqual:
1774 case AsmToken::Percent:
1775 case AsmToken::Less:
1776 case AsmToken::LessEqual:
1777 case AsmToken::LessLess:
1778 case AsmToken::LessGreater:
1779 case AsmToken::Greater:
1780 case AsmToken::GreaterEqual:
1781 case AsmToken::GreaterGreater:
1782 return true;
1783 }
1784}
1785
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001786bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001787 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001788 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001789 unsigned AddTokens = 0;
1790
1791 // gas accepts arguments separated by whitespace, except on Darwin
1792 if (!IsDarwin)
1793 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001794
1795 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001796 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1797 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001798 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001799 }
1800
1801 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1802 // Spaces and commas cannot be mixed to delimit parameters
1803 if (ArgumentDelimiter == AsmToken::Eof)
1804 ArgumentDelimiter = AsmToken::Comma;
1805 else if (ArgumentDelimiter != AsmToken::Comma) {
1806 Lexer.setSkipSpace(true);
1807 return TokError("expected ' ' for macro argument separator");
1808 }
1809 break;
1810 }
1811
1812 if (Lexer.is(AsmToken::Space)) {
1813 Lex(); // Eat spaces
1814
1815 // Spaces can delimit parameters, but could also be part an expression.
1816 // If the token after a space is an operator, add the token and the next
1817 // one into this argument
1818 if (ArgumentDelimiter == AsmToken::Space ||
1819 ArgumentDelimiter == AsmToken::Eof) {
1820 if (IsOperator(Lexer.getKind())) {
1821 // Check to see whether the token is used as an operator,
1822 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001823 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001824 if (*NextChar == ' ')
1825 AddTokens = 2;
1826 }
1827
1828 if (!AddTokens && ParenLevel == 0) {
1829 if (ArgumentDelimiter == AsmToken::Eof &&
1830 !IsOperator(Lexer.getKind()))
1831 ArgumentDelimiter = AsmToken::Space;
1832 break;
1833 }
1834 }
1835 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001836
1837 // HandleMacroEntry relies on not advancing the lexer here
1838 // to be able to fill in the remaining default parameter values
1839 if (Lexer.is(AsmToken::EndOfStatement))
1840 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001841
1842 // Adjust the current parentheses level.
1843 if (Lexer.is(AsmToken::LParen))
1844 ++ParenLevel;
1845 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1846 --ParenLevel;
1847
1848 // Append the token to the current argument list.
1849 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001850 if (AddTokens)
1851 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001852 Lex();
1853 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001854
1855 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001856 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001857 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001858 return false;
1859}
1860
1861// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001862bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001863 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001864 // Argument delimiter is initially unknown. It will be set by
1865 // ParseMacroArgument()
1866 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001867
1868 // Parse two kinds of macro invocations:
1869 // - macros defined without any parameters accept an arbitrary number of them
1870 // - macros defined with parameters accept at most that many of them
1871 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1872 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001873 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001874
Preston Gurd7b6f2032012-09-19 20:36:12 +00001875 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001876 return true;
1877
Preston Gurd6c9176a2012-09-19 20:29:04 +00001878 if (!MA.empty() || !NParameters)
1879 A.push_back(MA);
1880 else if (NParameters) {
1881 if (!M->Parameters[Parameter].second.empty())
1882 A.push_back(M->Parameters[Parameter].second);
1883 }
Jim Grosbach97146442012-07-30 22:44:17 +00001884
Preston Gurd6c9176a2012-09-19 20:29:04 +00001885 // At the end of the statement, fill in remaining arguments that have
1886 // default values. If there aren't any, then the next argument is
1887 // required but missing
1888 if (Lexer.is(AsmToken::EndOfStatement)) {
1889 if (NParameters && Parameter < NParameters - 1) {
1890 if (M->Parameters[Parameter + 1].second.empty())
1891 return TokError("macro argument '" +
1892 Twine(M->Parameters[Parameter + 1].first) +
1893 "' is missing");
1894 else
1895 continue;
1896 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001897 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001898 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001899
1900 if (Lexer.is(AsmToken::Comma))
1901 Lex();
1902 }
1903 return TokError("Too many arguments");
1904}
1905
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001906const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1907 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1908 return (I == MacroMap.end()) ? NULL : I->getValue();
1909}
1910
1911void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1912 MacroMap[Name] = new MCAsmMacro(Macro);
1913}
1914
1915void AsmParser::UndefineMacro(StringRef Name) {
1916 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1917 if (I != MacroMap.end()) {
1918 delete I->getValue();
1919 MacroMap.erase(I);
1920 }
1921}
1922
1923bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001924 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1925 // this, although we should protect against infinite loops.
1926 if (ActiveMacros.size() == 20)
1927 return TokError("macros cannot be nested more than 20 levels deep");
1928
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001929 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001930 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001931 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001932
Jim Grosbach97146442012-07-30 22:44:17 +00001933 // Remove any trailing empty arguments. Do this after-the-fact as we have
1934 // to keep empty arguments in the middle of the list or positionality
1935 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001936 while (!A.empty() && A.back().empty())
1937 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001938
Rafael Espindola65366442011-06-05 02:43:45 +00001939 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1940 // to hold the macro body with substitutions.
1941 SmallString<256> Buf;
1942 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001943 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001944
Rafael Espindola8a403d32012-08-08 14:51:03 +00001945 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001946 return true;
1947
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001948 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001949 // instantiation.
1950 OS << ".endmacro\n";
1951
Rafael Espindola65366442011-06-05 02:43:45 +00001952 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001953 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001954
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001955 // Create the macro instantiation object and add to the current macro
1956 // instantiation stack.
1957 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001958 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001959 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001960 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001961 ActiveMacros.push_back(MI);
1962
1963 // Jump to the macro instantiation and prime the lexer.
1964 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1965 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1966 Lex();
1967
1968 return false;
1969}
1970
1971void AsmParser::HandleMacroExit() {
1972 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001973 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001974 Lex();
1975
1976 // Pop the instantiation entry.
1977 delete ActiveMacros.back();
1978 ActiveMacros.pop_back();
1979}
1980
Rafael Espindolae71cc862012-01-28 05:57:00 +00001981static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001982 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001983 case MCExpr::Binary: {
1984 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1985 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001986 break;
1987 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001988 case MCExpr::Target:
1989 case MCExpr::Constant:
1990 return false;
1991 case MCExpr::SymbolRef: {
1992 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001993 if (S.isVariable())
1994 return IsUsedIn(Sym, S.getVariableValue());
1995 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001996 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001997 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001998 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001999 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002000
2001 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002002}
2003
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002004bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2005 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002006 // FIXME: Use better location, we should use proper tokens.
2007 SMLoc EqualLoc = Lexer.getLoc();
2008
Daniel Dunbar821e3332009-08-31 08:09:28 +00002009 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002010 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002011 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002012
Rafael Espindolae71cc862012-01-28 05:57:00 +00002013 // Note: we don't count b as used in "a = b". This is to allow
2014 // a = b
2015 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002016
Daniel Dunbar3f872332009-07-28 16:08:33 +00002017 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002018 return TokError("unexpected token in assignment");
2019
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002020 // Error on assignment to '.'.
2021 if (Name == ".") {
2022 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2023 "(use '.space' or '.org').)"));
2024 }
2025
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002026 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002027 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002028
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002029 // Validate that the LHS is allowed to be a variable (either it has not been
2030 // used as a symbol, or it is an absolute symbol).
2031 MCSymbol *Sym = getContext().LookupSymbol(Name);
2032 if (Sym) {
2033 // Diagnose assignment to a label.
2034 //
2035 // FIXME: Diagnostics. Note the location of the definition as a label.
2036 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002037 if (IsUsedIn(Sym, Value))
2038 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2039 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002040 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002041 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2042 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002043 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002044 return Error(EqualLoc, "redefinition of '" + Name + "'");
2045 else if (!Sym->isVariable())
2046 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002047 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002048 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2049 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002050
2051 // Don't count these checks as uses.
2052 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002053 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002054 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002055
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002056 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002057
2058 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002059 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002060 if (NoDeadStrip)
2061 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2062
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002063
2064 return false;
2065}
2066
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002067/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002068/// ::= identifier
2069/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002070bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002071 // The assembler has relaxed rules for accepting identifiers, in particular we
2072 // allow things like '.globl $foo', which would normally be separate
2073 // tokens. At this level, we have already lexed so we cannot (currently)
2074 // handle this as a context dependent token, instead we detect adjacent tokens
2075 // and return the combined identifier.
2076 if (Lexer.is(AsmToken::Dollar)) {
2077 SMLoc DollarLoc = getLexer().getLoc();
2078
2079 // Consume the dollar sign, and check for a following identifier.
2080 Lex();
2081 if (Lexer.isNot(AsmToken::Identifier))
2082 return true;
2083
2084 // We have a '$' followed by an identifier, make sure they are adjacent.
2085 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2086 return true;
2087
2088 // Construct the joined identifier and consume the token.
2089 Res = StringRef(DollarLoc.getPointer(),
2090 getTok().getIdentifier().size() + 1);
2091 Lex();
2092 return false;
2093 }
2094
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002095 if (Lexer.isNot(AsmToken::Identifier) &&
2096 Lexer.isNot(AsmToken::String))
2097 return true;
2098
Sean Callanan18b83232010-01-19 21:44:56 +00002099 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002100
Sean Callanan79ed1a82010-01-19 20:22:31 +00002101 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002102
2103 return false;
2104}
2105
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002106/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002107/// ::= .equ identifier ',' expression
2108/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002109/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002110bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002111 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002112
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002113 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002114 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002115
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002116 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002117 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002118 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002119
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002120 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002121}
2122
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002123bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002124 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002125
2126 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002127 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002128 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2129 if (Str[i] != '\\') {
2130 Data += Str[i];
2131 continue;
2132 }
2133
2134 // Recognize escaped characters. Note that this escape semantics currently
2135 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2136 ++i;
2137 if (i == e)
2138 return TokError("unexpected backslash at end of string");
2139
2140 // Recognize octal sequences.
2141 if ((unsigned) (Str[i] - '0') <= 7) {
2142 // Consume up to three octal characters.
2143 unsigned Value = Str[i] - '0';
2144
2145 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2146 ++i;
2147 Value = Value * 8 + (Str[i] - '0');
2148
2149 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2150 ++i;
2151 Value = Value * 8 + (Str[i] - '0');
2152 }
2153 }
2154
2155 if (Value > 255)
2156 return TokError("invalid octal escape sequence (out of range)");
2157
2158 Data += (unsigned char) Value;
2159 continue;
2160 }
2161
2162 // Otherwise recognize individual escapes.
2163 switch (Str[i]) {
2164 default:
2165 // Just reject invalid escape sequences for now.
2166 return TokError("invalid escape sequence (unrecognized character)");
2167
2168 case 'b': Data += '\b'; break;
2169 case 'f': Data += '\f'; break;
2170 case 'n': Data += '\n'; break;
2171 case 'r': Data += '\r'; break;
2172 case 't': Data += '\t'; break;
2173 case '"': Data += '"'; break;
2174 case '\\': Data += '\\'; break;
2175 }
2176 }
2177
2178 return false;
2179}
2180
Daniel Dunbara0d14262009-06-24 23:30:00 +00002181/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002182/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2183bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002184 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002185 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002186
Daniel Dunbara0d14262009-06-24 23:30:00 +00002187 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002188 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002189 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002190
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002191 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002192 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002193 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002194
2195 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002196 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002197 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2198
Sean Callanan79ed1a82010-01-19 20:22:31 +00002199 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002200
2201 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002202 break;
2203
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002204 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002205 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002206 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002207 }
2208 }
2209
Sean Callanan79ed1a82010-01-19 20:22:31 +00002210 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002211 return false;
2212}
2213
2214/// ParseDirectiveValue
2215/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2216bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002218 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002219
Daniel Dunbara0d14262009-06-24 23:30:00 +00002220 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002221 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002222 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002223 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 return true;
2225
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002226 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002227 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2228 assert(Size <= 8 && "Invalid size");
2229 uint64_t IntValue = MCE->getValue();
2230 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2231 return Error(ExprLoc, "literal value out of range for directive");
2232 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2233 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002234 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002235
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002236 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002237 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002238
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002240 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002241 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002242 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002243 }
2244 }
2245
Sean Callanan79ed1a82010-01-19 20:22:31 +00002246 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002247 return false;
2248}
2249
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002250/// ParseDirectiveRealValue
2251/// ::= (.single | .double) [ expression (, expression)* ]
2252bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2253 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002254 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002255
2256 for (;;) {
2257 // We don't truly support arithmetic on floating point expressions, so we
2258 // have to manually parse unary prefixes.
2259 bool IsNeg = false;
2260 if (getLexer().is(AsmToken::Minus)) {
2261 Lex();
2262 IsNeg = true;
2263 } else if (getLexer().is(AsmToken::Plus))
2264 Lex();
2265
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002266 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002267 getLexer().isNot(AsmToken::Real) &&
2268 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002269 return TokError("unexpected token in directive");
2270
2271 // Convert to an APFloat.
2272 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002273 StringRef IDVal = getTok().getString();
2274 if (getLexer().is(AsmToken::Identifier)) {
2275 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2276 Value = APFloat::getInf(Semantics);
2277 else if (!IDVal.compare_lower("nan"))
2278 Value = APFloat::getNaN(Semantics, false, ~0);
2279 else
2280 return TokError("invalid floating point literal");
2281 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002282 APFloat::opInvalidOp)
2283 return TokError("invalid floating point literal");
2284 if (IsNeg)
2285 Value.changeSign();
2286
2287 // Consume the numeric token.
2288 Lex();
2289
2290 // Emit the value as an integer.
2291 APInt AsInt = Value.bitcastToAPInt();
2292 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2293 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2294
2295 if (getLexer().is(AsmToken::EndOfStatement))
2296 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002297
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002298 if (getLexer().isNot(AsmToken::Comma))
2299 return TokError("unexpected token in directive");
2300 Lex();
2301 }
2302 }
2303
2304 Lex();
2305 return false;
2306}
2307
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002308/// ParseDirectiveZero
2309/// ::= .zero expression
2310bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002311 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002312
2313 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002314 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002315 return true;
2316
Rafael Espindolae452b172010-10-05 19:42:57 +00002317 int64_t Val = 0;
2318 if (getLexer().is(AsmToken::Comma)) {
2319 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002320 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002321 return true;
2322 }
2323
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002324 if (getLexer().isNot(AsmToken::EndOfStatement))
2325 return TokError("unexpected token in '.zero' directive");
2326
2327 Lex();
2328
Rafael Espindolae452b172010-10-05 19:42:57 +00002329 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002330
2331 return false;
2332}
2333
Daniel Dunbara0d14262009-06-24 23:30:00 +00002334/// ParseDirectiveFill
2335/// ::= .fill expression , expression , expression
2336bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002337 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002338
Daniel Dunbara0d14262009-06-24 23:30:00 +00002339 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002340 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002341 return true;
2342
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002343 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002344 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002345 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002346
Daniel Dunbara0d14262009-06-24 23:30:00 +00002347 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002348 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002349 return true;
2350
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002351 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002352 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002353 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002354
Daniel Dunbara0d14262009-06-24 23:30:00 +00002355 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002356 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002357 return true;
2358
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002359 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002360 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002361
Sean Callanan79ed1a82010-01-19 20:22:31 +00002362 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002363
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002364 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2365 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002366
2367 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002368 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002369
2370 return false;
2371}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002372
2373/// ParseDirectiveOrg
2374/// ::= .org expression [ , expression ]
2375bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002376 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002377
Daniel Dunbar821e3332009-08-31 08:09:28 +00002378 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002379 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002380 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002381 return true;
2382
2383 // Parse optional fill expression.
2384 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002385 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2386 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002387 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002388 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002389
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002390 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002391 return true;
2392
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002393 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002394 return TokError("unexpected token in '.org' directive");
2395 }
2396
Sean Callanan79ed1a82010-01-19 20:22:31 +00002397 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002398
Jim Grosbachebd4c052012-01-27 00:37:08 +00002399 // Only limited forms of relocatable expressions are accepted here, it
2400 // has to be relative to the current section. The streamer will return
2401 // 'true' if the expression wasn't evaluatable.
2402 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2403 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002404
2405 return false;
2406}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002407
2408/// ParseDirectiveAlign
2409/// ::= {.align, ...} expression [ , expression [ , expression ]]
2410bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002411 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002412
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002413 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002414 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002415 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002416 return true;
2417
2418 SMLoc MaxBytesLoc;
2419 bool HasFillExpr = false;
2420 int64_t FillExpr = 0;
2421 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2423 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002424 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002425 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426
2427 // The fill expression can be omitted while specifying a maximum number of
2428 // alignment bytes, e.g:
2429 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002430 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002431 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002432 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002433 return true;
2434 }
2435
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002436 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2437 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002438 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002439 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002440
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002441 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002442 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002444
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002445 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002446 return TokError("unexpected token in directive");
2447 }
2448 }
2449
Sean Callanan79ed1a82010-01-19 20:22:31 +00002450 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002451
Daniel Dunbar648ac512010-05-17 21:54:30 +00002452 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002453 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002454
2455 // Compute alignment in bytes.
2456 if (IsPow2) {
2457 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002458 if (Alignment >= 32) {
2459 Error(AlignmentLoc, "invalid alignment value");
2460 Alignment = 31;
2461 }
2462
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002463 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002464 } else {
2465 // Reject alignments that aren't a power of two, for gas compatibility.
2466 if (!isPowerOf2_64(Alignment))
2467 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002468 }
2469
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002470 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002471 if (MaxBytesLoc.isValid()) {
2472 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002473 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2474 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002475 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002476 }
2477
2478 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002479 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2480 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002481 MaxBytesToFill = 0;
2482 }
2483 }
2484
Daniel Dunbar648ac512010-05-17 21:54:30 +00002485 // Check whether we should use optimal code alignment for this .align
2486 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002487 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002488 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2489 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002490 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002491 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002492 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002493 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2494 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002495 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002496
2497 return false;
2498}
2499
Eli Bendersky6ee13082013-01-15 22:59:42 +00002500/// ParseDirectiveFile
2501/// ::= .file [number] filename
2502/// ::= .file number directory filename
2503bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2504 // FIXME: I'm not sure what this is.
2505 int64_t FileNumber = -1;
2506 SMLoc FileNumberLoc = getLexer().getLoc();
2507 if (getLexer().is(AsmToken::Integer)) {
2508 FileNumber = getTok().getIntVal();
2509 Lex();
2510
2511 if (FileNumber < 1)
2512 return TokError("file number less than one");
2513 }
2514
2515 if (getLexer().isNot(AsmToken::String))
2516 return TokError("unexpected token in '.file' directive");
2517
2518 // Usually the directory and filename together, otherwise just the directory.
2519 StringRef Path = getTok().getString();
2520 Path = Path.substr(1, Path.size()-2);
2521 Lex();
2522
2523 StringRef Directory;
2524 StringRef Filename;
2525 if (getLexer().is(AsmToken::String)) {
2526 if (FileNumber == -1)
2527 return TokError("explicit path specified, but no file number");
2528 Filename = getTok().getString();
2529 Filename = Filename.substr(1, Filename.size()-2);
2530 Directory = Path;
2531 Lex();
2532 } else {
2533 Filename = Path;
2534 }
2535
2536 if (getLexer().isNot(AsmToken::EndOfStatement))
2537 return TokError("unexpected token in '.file' directive");
2538
2539 if (FileNumber == -1)
2540 getStreamer().EmitFileDirective(Filename);
2541 else {
2542 if (getContext().getGenDwarfForAssembly() == true)
2543 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2544 "used to generate dwarf debug info for assembly code");
2545
2546 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2547 Error(FileNumberLoc, "file number already allocated");
2548 }
2549
2550 return false;
2551}
2552
2553/// ParseDirectiveLine
2554/// ::= .line [number]
2555bool AsmParser::ParseDirectiveLine() {
2556 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2557 if (getLexer().isNot(AsmToken::Integer))
2558 return TokError("unexpected token in '.line' directive");
2559
2560 int64_t LineNumber = getTok().getIntVal();
2561 (void) LineNumber;
2562 Lex();
2563
2564 // FIXME: Do something with the .line.
2565 }
2566
2567 if (getLexer().isNot(AsmToken::EndOfStatement))
2568 return TokError("unexpected token in '.line' directive");
2569
2570 return false;
2571}
2572
2573/// ParseDirectiveLoc
2574/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2575/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2576/// The first number is a file number, must have been previously assigned with
2577/// a .file directive, the second number is the line number and optionally the
2578/// third number is a column position (zero if not specified). The remaining
2579/// optional items are .loc sub-directives.
2580bool AsmParser::ParseDirectiveLoc() {
2581 if (getLexer().isNot(AsmToken::Integer))
2582 return TokError("unexpected token in '.loc' directive");
2583 int64_t FileNumber = getTok().getIntVal();
2584 if (FileNumber < 1)
2585 return TokError("file number less than one in '.loc' directive");
2586 if (!getContext().isValidDwarfFileNumber(FileNumber))
2587 return TokError("unassigned file number in '.loc' directive");
2588 Lex();
2589
2590 int64_t LineNumber = 0;
2591 if (getLexer().is(AsmToken::Integer)) {
2592 LineNumber = getTok().getIntVal();
2593 if (LineNumber < 1)
2594 return TokError("line number less than one in '.loc' directive");
2595 Lex();
2596 }
2597
2598 int64_t ColumnPos = 0;
2599 if (getLexer().is(AsmToken::Integer)) {
2600 ColumnPos = getTok().getIntVal();
2601 if (ColumnPos < 0)
2602 return TokError("column position less than zero in '.loc' directive");
2603 Lex();
2604 }
2605
2606 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2607 unsigned Isa = 0;
2608 int64_t Discriminator = 0;
2609 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2610 for (;;) {
2611 if (getLexer().is(AsmToken::EndOfStatement))
2612 break;
2613
2614 StringRef Name;
2615 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002616 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002617 return TokError("unexpected token in '.loc' directive");
2618
2619 if (Name == "basic_block")
2620 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2621 else if (Name == "prologue_end")
2622 Flags |= DWARF2_FLAG_PROLOGUE_END;
2623 else if (Name == "epilogue_begin")
2624 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2625 else if (Name == "is_stmt") {
2626 Loc = getTok().getLoc();
2627 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002628 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002629 return true;
2630 // The expression must be the constant 0 or 1.
2631 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2632 int Value = MCE->getValue();
2633 if (Value == 0)
2634 Flags &= ~DWARF2_FLAG_IS_STMT;
2635 else if (Value == 1)
2636 Flags |= DWARF2_FLAG_IS_STMT;
2637 else
2638 return Error(Loc, "is_stmt value not 0 or 1");
2639 }
2640 else {
2641 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2642 }
2643 }
2644 else if (Name == "isa") {
2645 Loc = getTok().getLoc();
2646 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002647 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002648 return true;
2649 // The expression must be a constant greater or equal to 0.
2650 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2651 int Value = MCE->getValue();
2652 if (Value < 0)
2653 return Error(Loc, "isa number less than zero");
2654 Isa = Value;
2655 }
2656 else {
2657 return Error(Loc, "isa number not a constant value");
2658 }
2659 }
2660 else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002661 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002662 return true;
2663 }
2664 else {
2665 return Error(Loc, "unknown sub-directive in '.loc' directive");
2666 }
2667
2668 if (getLexer().is(AsmToken::EndOfStatement))
2669 break;
2670 }
2671 }
2672
2673 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2674 Isa, Discriminator, StringRef());
2675
2676 return false;
2677}
2678
2679/// ParseDirectiveStabs
2680/// ::= .stabs string, number, number, number
2681bool AsmParser::ParseDirectiveStabs() {
2682 return TokError("unsupported directive '.stabs'");
2683}
2684
2685/// ParseDirectiveCFISections
2686/// ::= .cfi_sections section [, section]
2687bool AsmParser::ParseDirectiveCFISections() {
2688 StringRef Name;
2689 bool EH = false;
2690 bool Debug = false;
2691
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002692 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002693 return TokError("Expected an identifier");
2694
2695 if (Name == ".eh_frame")
2696 EH = true;
2697 else if (Name == ".debug_frame")
2698 Debug = true;
2699
2700 if (getLexer().is(AsmToken::Comma)) {
2701 Lex();
2702
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002703 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002704 return TokError("Expected an identifier");
2705
2706 if (Name == ".eh_frame")
2707 EH = true;
2708 else if (Name == ".debug_frame")
2709 Debug = true;
2710 }
2711
2712 getStreamer().EmitCFISections(EH, Debug);
2713 return false;
2714}
2715
2716/// ParseDirectiveCFIStartProc
2717/// ::= .cfi_startproc
2718bool AsmParser::ParseDirectiveCFIStartProc() {
2719 getStreamer().EmitCFIStartProc();
2720 return false;
2721}
2722
2723/// ParseDirectiveCFIEndProc
2724/// ::= .cfi_endproc
2725bool AsmParser::ParseDirectiveCFIEndProc() {
2726 getStreamer().EmitCFIEndProc();
2727 return false;
2728}
2729
2730/// ParseRegisterOrRegisterNumber - parse register name or number.
2731bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2732 SMLoc DirectiveLoc) {
2733 unsigned RegNo;
2734
2735 if (getLexer().isNot(AsmToken::Integer)) {
2736 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2737 return true;
2738 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2739 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002740 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002741
2742 return false;
2743}
2744
2745/// ParseDirectiveCFIDefCfa
2746/// ::= .cfi_def_cfa register, offset
2747bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2748 int64_t Register = 0;
2749 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2750 return true;
2751
2752 if (getLexer().isNot(AsmToken::Comma))
2753 return TokError("unexpected token in directive");
2754 Lex();
2755
2756 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002757 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002758 return true;
2759
2760 getStreamer().EmitCFIDefCfa(Register, Offset);
2761 return false;
2762}
2763
2764/// ParseDirectiveCFIDefCfaOffset
2765/// ::= .cfi_def_cfa_offset offset
2766bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2767 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002768 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002769 return true;
2770
2771 getStreamer().EmitCFIDefCfaOffset(Offset);
2772 return false;
2773}
2774
2775/// ParseDirectiveCFIRegister
2776/// ::= .cfi_register register, register
2777bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2778 int64_t Register1 = 0;
2779 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2780 return true;
2781
2782 if (getLexer().isNot(AsmToken::Comma))
2783 return TokError("unexpected token in directive");
2784 Lex();
2785
2786 int64_t Register2 = 0;
2787 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2788 return true;
2789
2790 getStreamer().EmitCFIRegister(Register1, Register2);
2791 return false;
2792}
2793
2794/// ParseDirectiveCFIAdjustCfaOffset
2795/// ::= .cfi_adjust_cfa_offset adjustment
2796bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2797 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002798 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002799 return true;
2800
2801 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2802 return false;
2803}
2804
2805/// ParseDirectiveCFIDefCfaRegister
2806/// ::= .cfi_def_cfa_register register
2807bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2808 int64_t Register = 0;
2809 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2810 return true;
2811
2812 getStreamer().EmitCFIDefCfaRegister(Register);
2813 return false;
2814}
2815
2816/// ParseDirectiveCFIOffset
2817/// ::= .cfi_offset register, offset
2818bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2819 int64_t Register = 0;
2820 int64_t Offset = 0;
2821
2822 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2823 return true;
2824
2825 if (getLexer().isNot(AsmToken::Comma))
2826 return TokError("unexpected token in directive");
2827 Lex();
2828
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002829 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002830 return true;
2831
2832 getStreamer().EmitCFIOffset(Register, Offset);
2833 return false;
2834}
2835
2836/// ParseDirectiveCFIRelOffset
2837/// ::= .cfi_rel_offset register, offset
2838bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2839 int64_t Register = 0;
2840
2841 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2842 return true;
2843
2844 if (getLexer().isNot(AsmToken::Comma))
2845 return TokError("unexpected token in directive");
2846 Lex();
2847
2848 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002849 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002850 return true;
2851
2852 getStreamer().EmitCFIRelOffset(Register, Offset);
2853 return false;
2854}
2855
2856static bool isValidEncoding(int64_t Encoding) {
2857 if (Encoding & ~0xff)
2858 return false;
2859
2860 if (Encoding == dwarf::DW_EH_PE_omit)
2861 return true;
2862
2863 const unsigned Format = Encoding & 0xf;
2864 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2865 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2866 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2867 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2868 return false;
2869
2870 const unsigned Application = Encoding & 0x70;
2871 if (Application != dwarf::DW_EH_PE_absptr &&
2872 Application != dwarf::DW_EH_PE_pcrel)
2873 return false;
2874
2875 return true;
2876}
2877
2878/// ParseDirectiveCFIPersonalityOrLsda
2879/// IsPersonality true for cfi_personality, false for cfi_lsda
2880/// ::= .cfi_personality encoding, [symbol_name]
2881/// ::= .cfi_lsda encoding, [symbol_name]
2882bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2883 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002884 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002885 return true;
2886 if (Encoding == dwarf::DW_EH_PE_omit)
2887 return false;
2888
2889 if (!isValidEncoding(Encoding))
2890 return TokError("unsupported encoding.");
2891
2892 if (getLexer().isNot(AsmToken::Comma))
2893 return TokError("unexpected token in directive");
2894 Lex();
2895
2896 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002897 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002898 return TokError("expected identifier in directive");
2899
2900 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2901
2902 if (IsPersonality)
2903 getStreamer().EmitCFIPersonality(Sym, Encoding);
2904 else
2905 getStreamer().EmitCFILsda(Sym, Encoding);
2906 return false;
2907}
2908
2909/// ParseDirectiveCFIRememberState
2910/// ::= .cfi_remember_state
2911bool AsmParser::ParseDirectiveCFIRememberState() {
2912 getStreamer().EmitCFIRememberState();
2913 return false;
2914}
2915
2916/// ParseDirectiveCFIRestoreState
2917/// ::= .cfi_remember_state
2918bool AsmParser::ParseDirectiveCFIRestoreState() {
2919 getStreamer().EmitCFIRestoreState();
2920 return false;
2921}
2922
2923/// ParseDirectiveCFISameValue
2924/// ::= .cfi_same_value register
2925bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2926 int64_t Register = 0;
2927
2928 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2929 return true;
2930
2931 getStreamer().EmitCFISameValue(Register);
2932 return false;
2933}
2934
2935/// ParseDirectiveCFIRestore
2936/// ::= .cfi_restore register
2937bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2938 int64_t Register = 0;
2939 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2940 return true;
2941
2942 getStreamer().EmitCFIRestore(Register);
2943 return false;
2944}
2945
2946/// ParseDirectiveCFIEscape
2947/// ::= .cfi_escape expression[,...]
2948bool AsmParser::ParseDirectiveCFIEscape() {
2949 std::string Values;
2950 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002951 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002952 return true;
2953
2954 Values.push_back((uint8_t)CurrValue);
2955
2956 while (getLexer().is(AsmToken::Comma)) {
2957 Lex();
2958
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002959 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002960 return true;
2961
2962 Values.push_back((uint8_t)CurrValue);
2963 }
2964
2965 getStreamer().EmitCFIEscape(Values);
2966 return false;
2967}
2968
2969/// ParseDirectiveCFISignalFrame
2970/// ::= .cfi_signal_frame
2971bool AsmParser::ParseDirectiveCFISignalFrame() {
2972 if (getLexer().isNot(AsmToken::EndOfStatement))
2973 return Error(getLexer().getLoc(),
2974 "unexpected token in '.cfi_signal_frame'");
2975
2976 getStreamer().EmitCFISignalFrame();
2977 return false;
2978}
2979
2980/// ParseDirectiveCFIUndefined
2981/// ::= .cfi_undefined register
2982bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2983 int64_t Register = 0;
2984
2985 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2986 return true;
2987
2988 getStreamer().EmitCFIUndefined(Register);
2989 return false;
2990}
2991
2992/// ParseDirectiveMacrosOnOff
2993/// ::= .macros_on
2994/// ::= .macros_off
2995bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2996 if (getLexer().isNot(AsmToken::EndOfStatement))
2997 return Error(getLexer().getLoc(),
2998 "unexpected token in '" + Directive + "' directive");
2999
3000 SetMacrosEnabled(Directive == ".macros_on");
3001 return false;
3002}
3003
3004/// ParseDirectiveMacro
3005/// ::= .macro name [parameters]
3006bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3007 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003008 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003009 return TokError("expected identifier in '.macro' directive");
3010
3011 MCAsmMacroParameters Parameters;
3012 // Argument delimiter is initially unknown. It will be set by
3013 // ParseMacroArgument()
3014 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3015 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3016 for (;;) {
3017 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003018 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003019 return TokError("expected identifier in '.macro' directive");
3020
3021 if (getLexer().is(AsmToken::Equal)) {
3022 Lex();
3023 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3024 return true;
3025 }
3026
3027 Parameters.push_back(Parameter);
3028
3029 if (getLexer().is(AsmToken::Comma))
3030 Lex();
3031 else if (getLexer().is(AsmToken::EndOfStatement))
3032 break;
3033 }
3034 }
3035
3036 // Eat the end of statement.
3037 Lex();
3038
3039 AsmToken EndToken, StartToken = getTok();
3040
3041 // Lex the macro definition.
3042 for (;;) {
3043 // Check whether we have reached the end of the file.
3044 if (getLexer().is(AsmToken::Eof))
3045 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3046
3047 // Otherwise, check whether we have reach the .endmacro.
3048 if (getLexer().is(AsmToken::Identifier) &&
3049 (getTok().getIdentifier() == ".endm" ||
3050 getTok().getIdentifier() == ".endmacro")) {
3051 EndToken = getTok();
3052 Lex();
3053 if (getLexer().isNot(AsmToken::EndOfStatement))
3054 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3055 "' directive");
3056 break;
3057 }
3058
3059 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003060 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003061 }
3062
3063 if (LookupMacro(Name)) {
3064 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3065 }
3066
3067 const char *BodyStart = StartToken.getLoc().getPointer();
3068 const char *BodyEnd = EndToken.getLoc().getPointer();
3069 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003070 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003071 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3072 return false;
3073}
3074
Kevin Enderby221514e2013-01-22 21:44:53 +00003075/// CheckForBadMacro
3076///
3077/// With the support added for named parameters there may be code out there that
3078/// is transitioning from positional parameters. In versions of gas that did
3079/// not support named parameters they would be ignored on the macro defintion.
3080/// But to support both styles of parameters this is not possible so if a macro
3081/// defintion has named parameters but does not use them and has what appears
3082/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3083/// warning that the positional parameter found in body which have no effect.
3084/// Hoping the developer will either remove the named parameters from the macro
3085/// definiton so the positional parameters get used if that was what was
3086/// intended or change the macro to use the named parameters. It is possible
3087/// this warning will trigger when the none of the named parameters are used
3088/// and the strings like $1 are infact to simply to be passed trough unchanged.
3089void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3090 StringRef Body,
3091 MCAsmMacroParameters Parameters) {
3092 // If this macro is not defined with named parameters the warning we are
3093 // checking for here doesn't apply.
3094 unsigned NParameters = Parameters.size();
3095 if (NParameters == 0)
3096 return;
3097
3098 bool NamedParametersFound = false;
3099 bool PositionalParametersFound = false;
3100
3101 // Look at the body of the macro for use of both the named parameters and what
3102 // are likely to be positional parameters. This is what expandMacro() is
3103 // doing when it finds the parameters in the body.
3104 while (!Body.empty()) {
3105 // Scan for the next possible parameter.
3106 std::size_t End = Body.size(), Pos = 0;
3107 for (; Pos != End; ++Pos) {
3108 // Check for a substitution or escape.
3109 // This macro is defined with parameters, look for \foo, \bar, etc.
3110 if (Body[Pos] == '\\' && Pos + 1 != End)
3111 break;
3112
3113 // This macro should have parameters, but look for $0, $1, ..., $n too.
3114 if (Body[Pos] != '$' || Pos + 1 == End)
3115 continue;
3116 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003117 if (Next == '$' || Next == 'n' ||
3118 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003119 break;
3120 }
3121
3122 // Check if we reached the end.
3123 if (Pos == End)
3124 break;
3125
3126 if (Body[Pos] == '$') {
3127 switch (Body[Pos+1]) {
3128 // $$ => $
3129 case '$':
3130 break;
3131
3132 // $n => number of arguments
3133 case 'n':
3134 PositionalParametersFound = true;
3135 break;
3136
3137 // $[0-9] => argument
3138 default: {
3139 PositionalParametersFound = true;
3140 break;
3141 }
3142 }
3143 Pos += 2;
3144 } else {
3145 unsigned I = Pos + 1;
3146 while (isIdentifierChar(Body[I]) && I + 1 != End)
3147 ++I;
3148
3149 const char *Begin = Body.data() + Pos +1;
3150 StringRef Argument(Begin, I - (Pos +1));
3151 unsigned Index = 0;
3152 for (; Index < NParameters; ++Index)
3153 if (Parameters[Index].first == Argument)
3154 break;
3155
3156 if (Index == NParameters) {
3157 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3158 Pos += 3;
3159 else {
3160 Pos = I;
3161 }
3162 } else {
3163 NamedParametersFound = true;
3164 Pos += 1 + Argument.size();
3165 }
3166 }
3167 // Update the scan point.
3168 Body = Body.substr(Pos);
3169 }
3170
3171 if (!NamedParametersFound && PositionalParametersFound)
3172 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3173 "used in macro body, possible positional parameter "
3174 "found in body which will have no effect");
3175}
3176
Eli Bendersky6ee13082013-01-15 22:59:42 +00003177/// ParseDirectiveEndMacro
3178/// ::= .endm
3179/// ::= .endmacro
3180bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3181 if (getLexer().isNot(AsmToken::EndOfStatement))
3182 return TokError("unexpected token in '" + Directive + "' directive");
3183
3184 // If we are inside a macro instantiation, terminate the current
3185 // instantiation.
3186 if (InsideMacroInstantiation()) {
3187 HandleMacroExit();
3188 return false;
3189 }
3190
3191 // Otherwise, this .endmacro is a stray entry in the file; well formed
3192 // .endmacro directives are handled during the macro definition parsing.
3193 return TokError("unexpected '" + Directive + "' in file, "
3194 "no current macro definition");
3195}
3196
3197/// ParseDirectivePurgeMacro
3198/// ::= .purgem
3199bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3200 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003201 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003202 return TokError("expected identifier in '.purgem' directive");
3203
3204 if (getLexer().isNot(AsmToken::EndOfStatement))
3205 return TokError("unexpected token in '.purgem' directive");
3206
3207 if (!LookupMacro(Name))
3208 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3209
3210 UndefineMacro(Name);
3211 return false;
3212}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003213
3214/// ParseDirectiveBundleAlignMode
3215/// ::= {.bundle_align_mode} expression
3216bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003217 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003218
3219 // Expect a single argument: an expression that evaluates to a constant
3220 // in the inclusive range 0-30.
3221 SMLoc ExprLoc = getLexer().getLoc();
3222 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003223 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003224 return true;
3225 else if (getLexer().isNot(AsmToken::EndOfStatement))
3226 return TokError("unexpected token after expression in"
3227 " '.bundle_align_mode' directive");
3228 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3229 return Error(ExprLoc,
3230 "invalid bundle alignment size (expected between 0 and 30)");
3231
3232 Lex();
3233
3234 // Because of AlignSizePow2's verified range we can safely truncate it to
3235 // unsigned.
3236 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3237 return false;
3238}
3239
3240/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003241/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003242bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003243 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003244 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003245
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003246 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3247 StringRef Option;
3248 SMLoc Loc = getTok().getLoc();
3249 const char *kInvalidOptionError =
3250 "invalid option for '.bundle_lock' directive";
3251
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003252 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003253 return Error(Loc, kInvalidOptionError);
3254
3255 if (Option != "align_to_end")
3256 return Error(Loc, kInvalidOptionError);
3257 else if (getLexer().isNot(AsmToken::EndOfStatement))
3258 return Error(Loc,
3259 "unexpected token after '.bundle_lock' directive option");
3260 AlignToEnd = true;
3261 }
3262
Eli Bendersky4766ef42012-12-20 19:05:53 +00003263 Lex();
3264
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003265 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003266 return false;
3267}
3268
3269/// ParseDirectiveBundleLock
3270/// ::= {.bundle_lock}
3271bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003272 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003273
3274 if (getLexer().isNot(AsmToken::EndOfStatement))
3275 return TokError("unexpected token in '.bundle_unlock' directive");
3276 Lex();
3277
3278 getStreamer().EmitBundleUnlock();
3279 return false;
3280}
3281
Eli Bendersky6ee13082013-01-15 22:59:42 +00003282/// ParseDirectiveSpace
3283/// ::= (.skip | .space) expression [ , expression ]
3284bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003285 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003286
3287 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003288 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003289 return true;
3290
3291 int64_t FillExpr = 0;
3292 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3293 if (getLexer().isNot(AsmToken::Comma))
3294 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3295 Lex();
3296
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003297 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003298 return true;
3299
3300 if (getLexer().isNot(AsmToken::EndOfStatement))
3301 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3302 }
3303
3304 Lex();
3305
3306 if (NumBytes <= 0)
3307 return TokError("invalid number of bytes in '" +
3308 Twine(IDVal) + "' directive");
3309
3310 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3311 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3312
3313 return false;
3314}
3315
3316/// ParseDirectiveLEB128
3317/// ::= (.sleb128 | .uleb128) expression
3318bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003319 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003320 const MCExpr *Value;
3321
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003322 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003323 return true;
3324
3325 if (getLexer().isNot(AsmToken::EndOfStatement))
3326 return TokError("unexpected token in directive");
3327
3328 if (Signed)
3329 getStreamer().EmitSLEB128Value(Value);
3330 else
3331 getStreamer().EmitULEB128Value(Value);
3332
3333 return false;
3334}
3335
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003336/// ParseDirectiveSymbolAttribute
3337/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003338bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003339 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003340 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003341 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003342 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003343
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003344 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003345 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003346
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003347 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003348
Jim Grosbach10ec6502011-09-15 17:56:49 +00003349 // Assembler local symbols don't make any sense here. Complain loudly.
3350 if (Sym->isTemporary())
3351 return Error(Loc, "non-local symbol required in directive");
3352
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003353 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003354
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003355 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003356 break;
3357
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003358 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003359 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003360 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003361 }
3362 }
3363
Sean Callanan79ed1a82010-01-19 20:22:31 +00003364 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003365 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003366}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003367
3368/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003369/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3370bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003371 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003372
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003373 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003374 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003375 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003376 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003377
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003378 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003379 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003380
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003381 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003382 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003383 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003384
3385 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003386 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003387 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003388 return true;
3389
3390 int64_t Pow2Alignment = 0;
3391 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003392 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003393 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003394 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003395 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003396 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003397
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003398 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3399 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003400 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3401
Chris Lattner258281d2010-01-19 06:22:22 +00003402 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003403 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3404 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003405 if (!isPowerOf2_64(Pow2Alignment))
3406 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3407 Pow2Alignment = Log2_64(Pow2Alignment);
3408 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003409 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003410
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003411 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003412 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003413
Sean Callanan79ed1a82010-01-19 20:22:31 +00003414 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003415
Chris Lattner1fc3d752009-07-09 17:25:12 +00003416 // NOTE: a size of zero for a .comm should create a undefined symbol
3417 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003418 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003419 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3420 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003421
Eric Christopherc260a3e2010-05-14 01:38:54 +00003422 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003423 // may internally end up wanting an alignment in bytes.
3424 // FIXME: Diagnose overflow.
3425 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003426 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3427 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003428
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003429 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003430 return Error(IDLoc, "invalid symbol redefinition");
3431
Chris Lattner1fc3d752009-07-09 17:25:12 +00003432 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003433 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003434 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003435 return false;
3436 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003437
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003438 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003439 return false;
3440}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003441
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003442/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003443/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003444bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003445 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003446 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003447
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003448 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003449 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003450 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003451
Sean Callanan79ed1a82010-01-19 20:22:31 +00003452 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003453
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003454 if (Str.empty())
3455 Error(Loc, ".abort detected. Assembly stopping.");
3456 else
3457 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003458 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003459
3460 return false;
3461}
Kevin Enderby71148242009-07-14 21:35:03 +00003462
Kevin Enderby1f049b22009-07-14 23:21:55 +00003463/// ParseDirectiveInclude
3464/// ::= .include "filename"
3465bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003466 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003467 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003468
Sean Callanan18b83232010-01-19 21:44:56 +00003469 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003470 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003471 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003472
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003473 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003474 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003475
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003476 // Strip the quotes.
3477 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003478
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003479 // Attempt to switch the lexer to the included file before consuming the end
3480 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003481 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003482 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003483 return true;
3484 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003485
3486 return false;
3487}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003488
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003489/// ParseDirectiveIncbin
3490/// ::= .incbin "filename"
3491bool AsmParser::ParseDirectiveIncbin() {
3492 if (getLexer().isNot(AsmToken::String))
3493 return TokError("expected string in '.incbin' directive");
3494
3495 std::string Filename = getTok().getString();
3496 SMLoc IncbinLoc = getLexer().getLoc();
3497 Lex();
3498
3499 if (getLexer().isNot(AsmToken::EndOfStatement))
3500 return TokError("unexpected token in '.incbin' directive");
3501
3502 // Strip the quotes.
3503 Filename = Filename.substr(1, Filename.size()-2);
3504
3505 // Attempt to process the included file.
3506 if (ProcessIncbinFile(Filename)) {
3507 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3508 return true;
3509 }
3510
3511 return false;
3512}
3513
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003514/// ParseDirectiveIf
3515/// ::= .if expression
3516bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003517 TheCondStack.push_back(TheCondState);
3518 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003519 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003520 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003521 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003522 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003523 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003524 return true;
3525
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003526 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003527 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003528
Sean Callanan79ed1a82010-01-19 20:22:31 +00003529 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003530
3531 TheCondState.CondMet = ExprValue;
3532 TheCondState.Ignore = !TheCondState.CondMet;
3533 }
3534
3535 return false;
3536}
3537
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003538/// ParseDirectiveIfb
3539/// ::= .ifb string
3540bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3541 TheCondStack.push_back(TheCondState);
3542 TheCondState.TheCond = AsmCond::IfCond;
3543
Benjamin Kramer29739e72012-05-12 16:52:21 +00003544 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003545 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003546 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003547 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003548
3549 if (getLexer().isNot(AsmToken::EndOfStatement))
3550 return TokError("unexpected token in '.ifb' directive");
3551
3552 Lex();
3553
3554 TheCondState.CondMet = ExpectBlank == Str.empty();
3555 TheCondState.Ignore = !TheCondState.CondMet;
3556 }
3557
3558 return false;
3559}
3560
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003561/// ParseDirectiveIfc
3562/// ::= .ifc string1, string2
3563bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3564 TheCondStack.push_back(TheCondState);
3565 TheCondState.TheCond = AsmCond::IfCond;
3566
Benjamin Kramer29739e72012-05-12 16:52:21 +00003567 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003568 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003569 } else {
3570 StringRef Str1 = ParseStringToComma();
3571
3572 if (getLexer().isNot(AsmToken::Comma))
3573 return TokError("unexpected token in '.ifc' directive");
3574
3575 Lex();
3576
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003577 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003578
3579 if (getLexer().isNot(AsmToken::EndOfStatement))
3580 return TokError("unexpected token in '.ifc' directive");
3581
3582 Lex();
3583
3584 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3585 TheCondState.Ignore = !TheCondState.CondMet;
3586 }
3587
3588 return false;
3589}
3590
3591/// ParseDirectiveIfdef
3592/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003593bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3594 StringRef Name;
3595 TheCondStack.push_back(TheCondState);
3596 TheCondState.TheCond = AsmCond::IfCond;
3597
3598 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003599 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003600 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003601 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003602 return TokError("expected identifier after '.ifdef'");
3603
3604 Lex();
3605
3606 MCSymbol *Sym = getContext().LookupSymbol(Name);
3607
3608 if (expect_defined)
3609 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3610 else
3611 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3612 TheCondState.Ignore = !TheCondState.CondMet;
3613 }
3614
3615 return false;
3616}
3617
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003618/// ParseDirectiveElseIf
3619/// ::= .elseif expression
3620bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3621 if (TheCondState.TheCond != AsmCond::IfCond &&
3622 TheCondState.TheCond != AsmCond::ElseIfCond)
3623 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3624 " an .elseif");
3625 TheCondState.TheCond = AsmCond::ElseIfCond;
3626
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003627 bool LastIgnoreState = false;
3628 if (!TheCondStack.empty())
3629 LastIgnoreState = TheCondStack.back().Ignore;
3630 if (LastIgnoreState || TheCondState.CondMet) {
3631 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003632 eatToEndOfStatement();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003633 }
3634 else {
3635 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003636 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003637 return true;
3638
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003639 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003640 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003641
Sean Callanan79ed1a82010-01-19 20:22:31 +00003642 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003643 TheCondState.CondMet = ExprValue;
3644 TheCondState.Ignore = !TheCondState.CondMet;
3645 }
3646
3647 return false;
3648}
3649
3650/// ParseDirectiveElse
3651/// ::= .else
3652bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003653 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003654 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003655
Sean Callanan79ed1a82010-01-19 20:22:31 +00003656 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003657
3658 if (TheCondState.TheCond != AsmCond::IfCond &&
3659 TheCondState.TheCond != AsmCond::ElseIfCond)
3660 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3661 ".elseif");
3662 TheCondState.TheCond = AsmCond::ElseCond;
3663 bool LastIgnoreState = false;
3664 if (!TheCondStack.empty())
3665 LastIgnoreState = TheCondStack.back().Ignore;
3666 if (LastIgnoreState || TheCondState.CondMet)
3667 TheCondState.Ignore = true;
3668 else
3669 TheCondState.Ignore = false;
3670
3671 return false;
3672}
3673
3674/// ParseDirectiveEndIf
3675/// ::= .endif
3676bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003677 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003678 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003679
Sean Callanan79ed1a82010-01-19 20:22:31 +00003680 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003681
3682 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3683 TheCondStack.empty())
3684 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3685 ".else");
3686 if (!TheCondStack.empty()) {
3687 TheCondState = TheCondStack.back();
3688 TheCondStack.pop_back();
3689 }
3690
3691 return false;
3692}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003693
Eli Bendersky6ee13082013-01-15 22:59:42 +00003694void AsmParser::initializeDirectiveKindMap() {
3695 DirectiveKindMap[".set"] = DK_SET;
3696 DirectiveKindMap[".equ"] = DK_EQU;
3697 DirectiveKindMap[".equiv"] = DK_EQUIV;
3698 DirectiveKindMap[".ascii"] = DK_ASCII;
3699 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3700 DirectiveKindMap[".string"] = DK_STRING;
3701 DirectiveKindMap[".byte"] = DK_BYTE;
3702 DirectiveKindMap[".short"] = DK_SHORT;
3703 DirectiveKindMap[".value"] = DK_VALUE;
3704 DirectiveKindMap[".2byte"] = DK_2BYTE;
3705 DirectiveKindMap[".long"] = DK_LONG;
3706 DirectiveKindMap[".int"] = DK_INT;
3707 DirectiveKindMap[".4byte"] = DK_4BYTE;
3708 DirectiveKindMap[".quad"] = DK_QUAD;
3709 DirectiveKindMap[".8byte"] = DK_8BYTE;
3710 DirectiveKindMap[".single"] = DK_SINGLE;
3711 DirectiveKindMap[".float"] = DK_FLOAT;
3712 DirectiveKindMap[".double"] = DK_DOUBLE;
3713 DirectiveKindMap[".align"] = DK_ALIGN;
3714 DirectiveKindMap[".align32"] = DK_ALIGN32;
3715 DirectiveKindMap[".balign"] = DK_BALIGN;
3716 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3717 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3718 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3719 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3720 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3721 DirectiveKindMap[".org"] = DK_ORG;
3722 DirectiveKindMap[".fill"] = DK_FILL;
3723 DirectiveKindMap[".zero"] = DK_ZERO;
3724 DirectiveKindMap[".extern"] = DK_EXTERN;
3725 DirectiveKindMap[".globl"] = DK_GLOBL;
3726 DirectiveKindMap[".global"] = DK_GLOBAL;
3727 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3728 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3729 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3730 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3731 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3732 DirectiveKindMap[".reference"] = DK_REFERENCE;
3733 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3734 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3735 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3736 DirectiveKindMap[".comm"] = DK_COMM;
3737 DirectiveKindMap[".common"] = DK_COMMON;
3738 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3739 DirectiveKindMap[".abort"] = DK_ABORT;
3740 DirectiveKindMap[".include"] = DK_INCLUDE;
3741 DirectiveKindMap[".incbin"] = DK_INCBIN;
3742 DirectiveKindMap[".code16"] = DK_CODE16;
3743 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3744 DirectiveKindMap[".rept"] = DK_REPT;
3745 DirectiveKindMap[".irp"] = DK_IRP;
3746 DirectiveKindMap[".irpc"] = DK_IRPC;
3747 DirectiveKindMap[".endr"] = DK_ENDR;
3748 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3749 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3750 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3751 DirectiveKindMap[".if"] = DK_IF;
3752 DirectiveKindMap[".ifb"] = DK_IFB;
3753 DirectiveKindMap[".ifnb"] = DK_IFNB;
3754 DirectiveKindMap[".ifc"] = DK_IFC;
3755 DirectiveKindMap[".ifnc"] = DK_IFNC;
3756 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3757 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3758 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3759 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3760 DirectiveKindMap[".else"] = DK_ELSE;
3761 DirectiveKindMap[".endif"] = DK_ENDIF;
3762 DirectiveKindMap[".skip"] = DK_SKIP;
3763 DirectiveKindMap[".space"] = DK_SPACE;
3764 DirectiveKindMap[".file"] = DK_FILE;
3765 DirectiveKindMap[".line"] = DK_LINE;
3766 DirectiveKindMap[".loc"] = DK_LOC;
3767 DirectiveKindMap[".stabs"] = DK_STABS;
3768 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3769 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3770 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3771 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3772 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3773 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3774 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3775 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3776 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3777 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3778 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3779 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3780 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3781 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3782 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3783 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3784 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3785 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3786 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3787 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3788 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3789 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3790 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3791 DirectiveKindMap[".macro"] = DK_MACRO;
3792 DirectiveKindMap[".endm"] = DK_ENDM;
3793 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3794 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003795}
3796
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003797
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003798MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003799 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003800
Rafael Espindola761cb062012-06-03 23:57:14 +00003801 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003802 for (;;) {
3803 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003804 if (getLexer().is(AsmToken::Eof)) {
3805 Error(DirectiveLoc, "no matching '.endr' in definition");
3806 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003807 }
3808
Rafael Espindola761cb062012-06-03 23:57:14 +00003809 if (Lexer.is(AsmToken::Identifier) &&
3810 (getTok().getIdentifier() == ".rept")) {
3811 ++NestLevel;
3812 }
3813
3814 // Otherwise, check whether we have reached the .endr.
3815 if (Lexer.is(AsmToken::Identifier) &&
3816 getTok().getIdentifier() == ".endr") {
3817 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003818 EndToken = getTok();
3819 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003820 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3821 TokError("unexpected token in '.endr' directive");
3822 return 0;
3823 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003824 break;
3825 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003826 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003827 }
3828
Rafael Espindola761cb062012-06-03 23:57:14 +00003829 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003830 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003831 }
3832
3833 const char *BodyStart = StartToken.getLoc().getPointer();
3834 const char *BodyEnd = EndToken.getLoc().getPointer();
3835 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3836
Rafael Espindola761cb062012-06-03 23:57:14 +00003837 // We Are Anonymous.
3838 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003839 MCAsmMacroParameters Parameters;
3840 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003841}
3842
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003843void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003844 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003845 OS << ".endr\n";
3846
3847 MemoryBuffer *Instantiation =
3848 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3849
Rafael Espindola761cb062012-06-03 23:57:14 +00003850 // Create the macro instantiation object and add to the current macro
3851 // instantiation stack.
3852 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003853 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003854 getTok().getLoc(),
3855 Instantiation);
3856 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003857
Rafael Espindola761cb062012-06-03 23:57:14 +00003858 // Jump to the macro instantiation and prime the lexer.
3859 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3860 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3861 Lex();
3862}
3863
3864bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3865 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003866 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003867 return TokError("unexpected token in '.rept' directive");
3868
3869 if (Count < 0)
3870 return TokError("Count is negative");
3871
3872 if (Lexer.isNot(AsmToken::EndOfStatement))
3873 return TokError("unexpected token in '.rept' directive");
3874
3875 // Eat the end of statement.
3876 Lex();
3877
3878 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003879 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003880 if (!M)
3881 return true;
3882
3883 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3884 // to hold the macro body with substitutions.
3885 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003886 MCAsmMacroParameters Parameters;
3887 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003888 raw_svector_ostream OS(Buf);
3889 while (Count--) {
3890 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3891 return true;
3892 }
3893 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003894
3895 return false;
3896}
3897
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003898/// ParseDirectiveIrp
3899/// ::= .irp symbol,values
3900bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003901 MCAsmMacroParameters Parameters;
3902 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003903
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003904 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003905 return TokError("expected identifier in '.irp' directive");
3906
3907 Parameters.push_back(Parameter);
3908
3909 if (Lexer.isNot(AsmToken::Comma))
3910 return TokError("expected comma in '.irp' directive");
3911
3912 Lex();
3913
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003914 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003915 if (ParseMacroArguments(0, A))
3916 return true;
3917
3918 // Eat the end of statement.
3919 Lex();
3920
3921 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003922 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003923 if (!M)
3924 return true;
3925
3926 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3927 // to hold the macro body with substitutions.
3928 SmallString<256> Buf;
3929 raw_svector_ostream OS(Buf);
3930
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003931 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3932 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003933 Args.push_back(*i);
3934
3935 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3936 return true;
3937 }
3938
3939 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3940
3941 return false;
3942}
3943
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003944/// ParseDirectiveIrpc
3945/// ::= .irpc symbol,values
3946bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003947 MCAsmMacroParameters Parameters;
3948 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003949
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003950 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003951 return TokError("expected identifier in '.irpc' directive");
3952
3953 Parameters.push_back(Parameter);
3954
3955 if (Lexer.isNot(AsmToken::Comma))
3956 return TokError("expected comma in '.irpc' directive");
3957
3958 Lex();
3959
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003960 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003961 if (ParseMacroArguments(0, A))
3962 return true;
3963
3964 if (A.size() != 1 || A.front().size() != 1)
3965 return TokError("unexpected token in '.irpc' directive");
3966
3967 // Eat the end of statement.
3968 Lex();
3969
3970 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003971 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003972 if (!M)
3973 return true;
3974
3975 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3976 // to hold the macro body with substitutions.
3977 SmallString<256> Buf;
3978 raw_svector_ostream OS(Buf);
3979
3980 StringRef Values = A.front().front().getString();
3981 std::size_t I, End = Values.size();
3982 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003983 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003984 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3985
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003986 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003987 Args.push_back(Arg);
3988
3989 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3990 return true;
3991 }
3992
3993 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3994
3995 return false;
3996}
3997
Rafael Espindola761cb062012-06-03 23:57:14 +00003998bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3999 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004000 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004001
4002 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004003 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004004 assert(getLexer().is(AsmToken::EndOfStatement));
4005
Rafael Espindola761cb062012-06-03 23:57:14 +00004006 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004007 return false;
4008}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004009
Benjamin Kramer75234372013-02-15 20:37:21 +00004010bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4011 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004012 const MCExpr *Value;
4013 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004014 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004015 return true;
4016 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4017 if (!MCE)
4018 return Error(ExprLoc, "unexpected expression in _emit");
4019 uint64_t IntValue = MCE->getValue();
4020 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4021 return Error(ExprLoc, "literal value out of range for directive");
4022
Chad Rosier469b1442013-02-12 21:33:51 +00004023 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4024 return false;
4025}
4026
4027bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4028 const MCExpr *Value;
4029 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004030 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004031 return true;
4032 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4033 if (!MCE)
4034 return Error(ExprLoc, "unexpected expression in align");
4035 uint64_t IntValue = MCE->getValue();
4036 if (!isPowerOf2_64(IntValue))
4037 return Error(ExprLoc, "literal value not a power of two greater then zero");
4038
Benjamin Kramer75234372013-02-15 20:37:21 +00004039 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4040 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004041 return false;
4042}
4043
Chad Rosier19aa3e32013-02-13 21:27:17 +00004044// We are comparing pointers, but the pointers are relative to a single string.
4045// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004046static int RewritesSort(const void *A, const void *B) {
4047 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4048 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004049 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4050 return -1;
4051 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4052 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004053
Chad Rosier6b369ce2013-04-08 17:43:47 +00004054 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4055 // rewrite to the same location. Make sure the SizeDirective rewrite is
4056 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4057 // ensures the sort algorithm is stable.
4058 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4059 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004060 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004061
4062 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4063 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004064 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004065 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004066}
4067
Benjamin Kramer75234372013-02-15 20:37:21 +00004068bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004069AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004070 unsigned &NumOutputs, unsigned &NumInputs,
4071 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4072 SmallVectorImpl<std::string> &Constraints,
4073 SmallVectorImpl<std::string> &Clobbers,
4074 const MCInstrInfo *MII,
4075 const MCInstPrinter *IP,
4076 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004077 SmallVector<void *, 4> InputDecls;
4078 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004079 SmallVector<bool, 4> InputDeclsAddressOf;
4080 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004081 SmallVector<std::string, 4> InputConstraints;
4082 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004083 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004084
Benjamin Kramer75234372013-02-15 20:37:21 +00004085 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004086
4087 // Prime the lexer.
4088 Lex();
4089
4090 // While we have input, parse each statement.
4091 unsigned InputIdx = 0;
4092 unsigned OutputIdx = 0;
4093 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004094 ParseStatementInfo Info(&AsmStrRewrites);
4095 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004096 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004097
Chad Rosier57498012012-12-12 22:45:52 +00004098 if (Info.ParseError)
4099 return true;
4100
Benjamin Kramer75234372013-02-15 20:37:21 +00004101 if (Info.Opcode == ~0U)
4102 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004103
Benjamin Kramer75234372013-02-15 20:37:21 +00004104 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004105
Benjamin Kramer75234372013-02-15 20:37:21 +00004106 // Build the list of clobbers, outputs and inputs.
4107 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4108 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004109
Benjamin Kramer75234372013-02-15 20:37:21 +00004110 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004111 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004112 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004113
Benjamin Kramer75234372013-02-15 20:37:21 +00004114 // Register operand.
4115 if (Operand->isReg() && !Operand->needAddressOf()) {
4116 unsigned NumDefs = Desc.getNumDefs();
4117 // Clobber.
4118 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4119 ClobberRegs.push_back(Operand->getReg());
4120 continue;
4121 }
4122
4123 // Expr/Input or Output.
4124 bool IsVarDecl;
4125 unsigned Length, Size, Type;
Chad Rosierb976e402013-04-09 17:53:49 +00004126 StringRef SymName = Operand->getSymName();
4127 if (SymName.empty())
4128 continue;
4129
4130 void *OpDecl = SI.LookupInlineAsmIdentifier(SymName, AsmLoc,
Benjamin Kramer75234372013-02-15 20:37:21 +00004131 Length, Size, Type,
4132 IsVarDecl);
4133 if (!OpDecl)
4134 continue;
4135
4136 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004137 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004138 if (isOutput) {
4139 ++InputIdx;
4140 OutputDecls.push_back(OpDecl);
4141 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4142 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004143 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004144 } else {
4145 InputDecls.push_back(OpDecl);
4146 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4147 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004148 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004149 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004150 }
4151 }
4152
4153 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004154 NumOutputs = OutputDecls.size();
4155 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004156
4157 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004158 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4159 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4160 ClobberRegs.end());
4161 Clobbers.assign(ClobberRegs.size(), std::string());
4162 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4163 raw_string_ostream OS(Clobbers[I]);
4164 IP->printRegName(OS, ClobberRegs[I]);
4165 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004166
4167 // Merge the various outputs and inputs. Output are expected first.
4168 if (NumOutputs || NumInputs) {
4169 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004170 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004171 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004172 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004173 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004174 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004175 }
4176 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004177 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004178 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004179 }
4180 }
4181
4182 // Build the IR assembly string.
4183 std::string AsmStringIR;
4184 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004185 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4186 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004187 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4188 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4189 E = AsmStrRewrites.end();
4190 I != E; ++I) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004191 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004192 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004193
Chad Rosier469b1442013-02-12 21:33:51 +00004194 unsigned AdditionalSkip = 0;
Chad Rosier4e472d22012-10-20 01:02:45 +00004195 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004196
Chad Rosier023c8802013-03-19 17:32:17 +00004197 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004198 unsigned Len = Loc - AsmStart;
4199 if (Len) {
4200 // For Input/Output operands we need to remove the brackets, if present.
4201 if ((Kind == AOK_Input || Kind == AOK_Output) && Loc[-1] == '[')
4202 --Len;
4203 OS << StringRef(AsmStart, Len);
4204 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004205
Chad Rosier5a719fc2012-10-23 17:43:43 +00004206 // Skip the original expression.
4207 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004208 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004209 continue;
4210 }
4211
Chad Rosierb1f8c132012-10-18 15:49:34 +00004212 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004213 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004214 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004215 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004216 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004217 break;
4218 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004219 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004220 break;
4221 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004222 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004223 break;
4224 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004225 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004226 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004227 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004228 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004229 default: break;
4230 case 8: OS << "byte ptr "; break;
4231 case 16: OS << "word ptr "; break;
4232 case 32: OS << "dword ptr "; break;
4233 case 64: OS << "qword ptr "; break;
4234 case 80: OS << "xword ptr "; break;
4235 case 128: OS << "xmmword ptr "; break;
4236 case 256: OS << "ymmword ptr "; break;
4237 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004238 break;
4239 case AOK_Emit:
4240 OS << ".byte";
4241 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004242 case AOK_Align: {
4243 unsigned Val = (*I).Val;
4244 OS << ".align " << Val;
4245
4246 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004247 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004248 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4249 break;
4250 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004251 case AOK_DotOperator:
4252 OS << (*I).Val;
4253 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004254 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004255
Chad Rosierb1f8c132012-10-18 15:49:34 +00004256 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004257 AsmStart = Loc + (*I).Len + AdditionalSkip;
4258
4259 // For Input/Output operands we need to remove the brackets, if present.
4260 if ((Kind == AOK_Input || Kind == AOK_Output) && AsmStart != AsmEnd &&
4261 *AsmStart == ']')
4262 ++AsmStart;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004263 }
4264
4265 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004266 if (AsmStart != AsmEnd)
4267 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004268
4269 AsmString = OS.str();
4270 return false;
4271}
4272
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004273/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004274MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004275 MCContext &C, MCStreamer &Out,
4276 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004277 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004278}