blob: b5f51d84845fbdb70676fff5536e4c6204be7cea [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"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Eric Christopher2318ba12012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000050
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000053/// \brief Helper types for tracking macro definitions.
54typedef std::vector<AsmToken> MCAsmMacroArgument;
55typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
57typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
58
59struct MCAsmMacro {
60 StringRef Name;
61 StringRef Body;
62 MCAsmMacroParameters Parameters;
63
64public:
65 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
67
68 MCAsmMacro(const MCAsmMacro& Other)
69 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
70};
71
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000072/// \brief Helper class for storing information about an active macro
73/// instantiation.
74struct MacroInstantiation {
75 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000076 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000077
78 /// The macro instantiation with substitutions.
79 MemoryBuffer *Instantiation;
80
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
83
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000084 /// The buffer where parsing should resume upon instantiation completion.
85 int ExitBuffer;
86
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000087 /// The location where parsing should resume upon instantiation completion.
88 SMLoc ExitLoc;
89
90public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000091 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000092 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000093};
94
Eli Friedman2128aae2012-10-22 23:58:19 +000095struct ParseStatementInfo {
96 /// ParsedOperands - The parsed operands from the last parsed statement.
97 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
98
99 /// Opcode - The opcode from the last parsed instruction.
100 unsigned Opcode;
101
Chad Rosier57498012012-12-12 22:45:52 +0000102 /// Error - Was there an error parsing the inline assembly?
103 bool ParseError;
104
Eli Friedman2128aae2012-10-22 23:58:19 +0000105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106
Chad Rosier57498012012-12-12 22:45:52 +0000107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000110
111 ~ParseStatementInfo() {
112 // Free any parsed operands.
113 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
114 delete ParsedOperands[i];
115 ParsedOperands.clear();
116 }
117};
118
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000119/// \brief The concrete assembly parser instance.
120class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000123private:
124 AsmLexer Lexer;
125 MCContext &Ctx;
126 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000127 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000132
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000133 /// This is the current buffer index we're lexing from as managed by the
134 /// SourceMgr object.
135 int CurBuffer;
136
137 AsmCond TheCondState;
138 std::vector<AsmCond> TheCondStack;
139
Eli Bendersky6ee13082013-01-15 22:59:42 +0000140 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
141 /// extensions. Extensions register themselves in this map by calling
142 /// AddDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000143 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000144
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000145 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000146 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000147
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000148 /// ActiveMacros - Stack of active macro instantiations.
149 std::vector<MacroInstantiation*> ActiveMacros;
150
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000151 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000152 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000153
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
156
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
160 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000161 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000162
Devang Patel0db58bf2012-01-31 18:14:05 +0000163 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
164 unsigned AssemblerDialect;
165
Preston Gurd7b6f2032012-09-19 20:36:12 +0000166 /// IsDarwin - is Darwin compatibility enabled?
167 bool IsDarwin;
168
Chad Rosier8f138d12012-10-15 17:19:13 +0000169 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000170 bool ParsingInlineAsm;
171
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000172public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000173 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000174 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000175 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000176
177 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
178
Eli Bendersky171192f2013-01-16 00:50:52 +0000179 virtual void AddDirectiveHandler(StringRef Directive,
180 ExtensionDirectiveHandler Handler) {
181 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182 }
183
184public:
185 /// @name MCAsmParser Interface
186 /// {
187
188 virtual SourceMgr &getSourceManager() { return SrcMgr; }
189 virtual MCAsmLexer &getLexer() { return Lexer; }
190 virtual MCContext &getContext() { return Ctx; }
191 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000192 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000193 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000194 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000195 else
196 return AssemblerDialect;
197 }
198 virtual void setAssemblerDialect(unsigned i) {
199 AssemblerDialect = i;
200 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000202 virtual bool Warning(SMLoc L, const Twine &Msg,
203 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual bool Error(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206
Craig Topper345d16d2012-08-29 05:48:09 +0000207 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000208
Chad Rosier84125ca2012-10-13 00:26:04 +0000209 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000210 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000211
212 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
213 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000214 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000215 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Clobbers,
217 const MCInstrInfo *MII,
218 const MCInstPrinter *IP,
219 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000220
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000221 bool ParseExpression(const MCExpr *&Res);
222 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
223 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseAbsoluteExpression(int64_t &Res);
225
Eli Benderskybf706b32013-01-12 00:05:00 +0000226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \p Res to the identifier contents.
228 virtual bool ParseIdentifier(StringRef &Res);
Eli Benderskyb2f0b592013-01-12 00:23:24 +0000229 virtual void EatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000230
Eli Bendersky318cad32013-01-14 19:15:01 +0000231 virtual void CheckForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000232 /// }
233
234private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000235
Eli Friedman2128aae2012-10-22 23:58:19 +0000236 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000239
Rafael Espindola761cb062012-06-03 23:57:14 +0000240 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000241 const MCAsmMacroParameters &Parameters,
242 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000243 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000244
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000245 /// \brief Are macros enabled in the parser?
246 bool MacrosEnabled() {return MacrosEnabledFlag;}
247
248 /// \brief Control a flag in the parser that enables or disables macros.
249 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
250
251 /// \brief Lookup a previously defined macro.
252 /// \param Name Macro name.
253 /// \returns Pointer to macro. NULL if no such macro was defined.
254 const MCAsmMacro* LookupMacro(StringRef Name);
255
256 /// \brief Define a new macro with the given name and information.
257 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
258
259 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
260 void UndefineMacro(StringRef Name);
261
262 /// \brief Are we inside a macro instantiation?
263 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
264
265 /// \brief Handle entry to macro instantiation.
266 ///
267 /// \param M The macro.
268 /// \param NameLoc Instantiation location.
269 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
270
271 /// \brief Handle exit from macro instantiation.
272 void HandleMacroExit();
273
274 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
275 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
276 /// correct delimiter by the method.
277 bool ParseMacroArgument(MCAsmMacroArgument &MA,
278 AsmToken::TokenKind &ArgumentDelimiter);
279
280 /// \brief Parse all macro arguments for a given macro.
281 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
282
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000283 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000284 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000285 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
286 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000287 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000288 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000289
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
291 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000292 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
293 /// This returns true on failure.
294 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000295
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000296 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000297 /// current token is not set; clients should ensure Lex() is called
298 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000299 ///
300 /// \param InBuffer If not -1, should be the known buffer id that contains the
301 /// location.
302 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000303
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000304 /// \brief Parse up to the end of statement and a return the contents from the
305 /// current token until the end of the statement; the current token on exit
306 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000307 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000308
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000309 /// \brief Parse until the end of a statement or a comma is encountered,
310 /// return the contents from the current token up to the end or comma.
311 StringRef ParseStringToComma();
312
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000313 bool ParseAssignment(StringRef Name, bool allow_redef,
314 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315
316 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
317 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
318 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000319 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000320
Eli Bendersky6ee13082013-01-15 22:59:42 +0000321 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000322
Eli Bendersky6ee13082013-01-15 22:59:42 +0000323 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000324 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000325 DK_NO_DIRECTIVE, // Placeholder
326 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
327 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
328 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000329 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000330 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
331 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
332 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
333 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
334 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
335 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
336 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000337 DK_ELSEIF, DK_ELSE, DK_ENDIF,
338 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
339 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
340 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
341 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
342 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
343 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
344 DK_CFI_REGISTER,
345 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
346 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000347 };
348
Eli Bendersky6ee13082013-01-15 22:59:42 +0000349 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
350 /// directives parsed by this class.
351 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000352
353 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000354 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000355 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000356 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000357 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000358 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000359 // ".set", ".equ", ".equiv"
360 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000361 bool ParseDirectiveOrg(); // ".org"
362 // ".align{,32}", ".p2align{,w,l}"
363 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
364
Eli Bendersky6ee13082013-01-15 22:59:42 +0000365 // ".file", ".line", ".loc", ".stabs"
366 bool ParseDirectiveFile(SMLoc DirectiveLoc);
367 bool ParseDirectiveLine();
368 bool ParseDirectiveLoc();
369 bool ParseDirectiveStabs();
370
371 // .cfi directives
372 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
373 bool ParseDirectiveCFISections();
374 bool ParseDirectiveCFIStartProc();
375 bool ParseDirectiveCFIEndProc();
376 bool ParseDirectiveCFIDefCfaOffset();
377 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIAdjustCfaOffset();
379 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
383 bool ParseDirectiveCFIRememberState();
384 bool ParseDirectiveCFIRestoreState();
385 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
387 bool ParseDirectiveCFIEscape();
388 bool ParseDirectiveCFISignalFrame();
389 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
390
391 // macro directives
392 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
393 bool ParseDirectiveEndMacro(StringRef Directive);
394 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveMacrosOnOff(StringRef Directive);
396
Eli Bendersky4766ef42012-12-20 19:05:53 +0000397 // ".bundle_align_mode"
398 bool ParseDirectiveBundleAlignMode();
399 // ".bundle_lock"
400 bool ParseDirectiveBundleLock();
401 // ".bundle_unlock"
402 bool ParseDirectiveBundleUnlock();
403
Eli Bendersky6ee13082013-01-15 22:59:42 +0000404 // ".space", ".skip"
405 bool ParseDirectiveSpace(StringRef IDVal);
406
407 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
408 bool ParseDirectiveLEB128(bool Signed);
409
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000410 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
411 /// accepts a single symbol (which should be a label or an external).
412 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000413
414 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
415
416 bool ParseDirectiveAbort(); // ".abort"
417 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000418 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000419
420 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000421 // ".ifb" or ".ifnb", depending on ExpectBlank.
422 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000423 // ".ifc" or ".ifnc", depending on ExpectEqual.
424 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000425 // ".ifdef" or ".ifndef", depending on expect_defined
426 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000427 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
428 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
429 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Daniel Dunbarbfdcc702013-01-18 01:25:33 +0000430 virtual bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000431
432 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
433 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000434
Rafael Espindola761cb062012-06-03 23:57:14 +0000435 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000436 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
437 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000438 raw_svector_ostream &OS);
439 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000440 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000441 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000442 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000443
Eli Friedman2128aae2012-10-22 23:58:19 +0000444 // "_emit"
445 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000446
Eli Bendersky6ee13082013-01-15 22:59:42 +0000447 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000448};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000449}
450
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000451namespace llvm {
452
453extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000454extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000455extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000456
457}
458
Chris Lattneraaec2052010-01-19 19:46:13 +0000459enum { DEFAULT_ADDRSPACE = 0 };
460
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000461AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000462 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000463 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000464 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000465 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000466 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000467 // Save the old handler.
468 SavedDiagHandler = SrcMgr.getDiagHandler();
469 SavedDiagContext = SrcMgr.getDiagContext();
470 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000471 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000472 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000473
Daniel Dunbare4749702010-07-12 18:12:02 +0000474 // Initialize the platform / file format parser.
475 //
476 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
477 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000478 if (_MAI.hasMicrosoftFastStdCallMangling()) {
479 PlatformParser = createCOFFAsmParser();
480 PlatformParser->Initialize(*this);
481 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000482 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000483 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000484 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000485 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000486 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000487 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000488 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000489
Eli Bendersky6ee13082013-01-15 22:59:42 +0000490 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000491}
492
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000493AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000494 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
495
496 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000497 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000498 ie = MacroMap.end(); it != ie; ++it)
499 delete it->getValue();
500
Daniel Dunbare4749702010-07-12 18:12:02 +0000501 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000502}
503
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000504void AsmParser::PrintMacroInstantiations() {
505 // Print the active macro instantiation stack.
506 for (std::vector<MacroInstantiation*>::const_reverse_iterator
507 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000508 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
509 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000510}
511
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000512bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000513 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000514 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000515 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000516 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000517 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000518}
519
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000520bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000521 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000522 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000523 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000524 return true;
525}
526
Sean Callananfd0b0282010-01-21 00:19:58 +0000527bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000528 std::string IncludedFile;
529 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000530 if (NewBuf == -1)
531 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000532
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000536
Sean Callananfd0b0282010-01-21 00:19:58 +0000537 return false;
538}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000539
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000540/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000541/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000542/// returns true on failure.
543bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
544 std::string IncludedFile;
545 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
546 if (NewBuf == -1)
547 return true;
548
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000549 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000550 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
551 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000552 return false;
553}
554
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000555void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
556 if (InBuffer != -1) {
557 CurBuffer = InBuffer;
558 } else {
559 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
560 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000561 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
562}
563
Sean Callananfd0b0282010-01-21 00:19:58 +0000564const AsmToken &AsmParser::Lex() {
565 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000566
Sean Callananfd0b0282010-01-21 00:19:58 +0000567 if (tok->is(AsmToken::Eof)) {
568 // If this is the end of an included file, pop the parent file off the
569 // include stack.
570 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
571 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000572 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000573 tok = &Lexer.Lex();
574 }
575 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000576
Sean Callananfd0b0282010-01-21 00:19:58 +0000577 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000578 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000581}
582
Chris Lattner79180e22010-04-05 23:15:42 +0000583bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000584 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000585 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000586 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000587
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000588 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000589 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000590
591 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000592 AsmCond StartingCondState = TheCondState;
593
Kevin Enderby613b7572011-11-01 22:27:22 +0000594 // If we are generating dwarf for assembly source files save the initial text
595 // section and generate a .file directive.
596 if (getContext().getGenDwarfForAssembly()) {
597 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000598 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
599 getStreamer().EmitLabel(SectionStartSym);
600 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000601 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000602 StringRef(),
603 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000604 }
605
Chris Lattnerb717fb02009-07-02 21:53:43 +0000606 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000607 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000608 ParseStatementInfo Info;
609 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000610
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000611 // We had an error, validate that one was emitted and recover by skipping to
612 // the next line.
613 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000614 EatToEndOfStatement();
615 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000616
617 if (TheCondState.TheCond != StartingCondState.TheCond ||
618 TheCondState.Ignore != StartingCondState.Ignore)
619 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000620
621 // Check to see there are no empty DwarfFile slots.
622 const std::vector<MCDwarfFile *> &MCDwarfFiles =
623 getContext().getMCDwarfFiles();
624 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000625 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000626 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000627 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000628
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000629 // Check to see that all assembler local symbols were actually defined.
630 // Targets that don't do subsections via symbols may not want this, though,
631 // so conservatively exclude them. Only do this if we're finalizing, though,
632 // as otherwise we won't necessarilly have seen everything yet.
633 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
634 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
635 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
636 e = Symbols.end();
637 i != e; ++i) {
638 MCSymbol *Sym = i->getValue();
639 // Variable symbols may not be marked as defined, so check those
640 // explicitly. If we know it's a variable, we have a definition for
641 // the purposes of this check.
642 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
643 // FIXME: We would really like to refer back to where the symbol was
644 // first referenced for a source location. We need to add something
645 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000646 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
647 "assembler local symbol '" + Sym->getName() +
648 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000649 }
650 }
651
652
Chris Lattner79180e22010-04-05 23:15:42 +0000653 // Finalize the output stream if there are no errors and if the client wants
654 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000655 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000656 Out.Finish();
657
Chris Lattnerb717fb02009-07-02 21:53:43 +0000658 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000659}
660
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000661void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000662 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000663 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000664 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000665 }
666}
667
Chris Lattner2cf5f142009-06-22 01:29:09 +0000668/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
669void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000670 while (Lexer.isNot(AsmToken::EndOfStatement) &&
671 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000672 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000673
Chris Lattner2cf5f142009-06-22 01:29:09 +0000674 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000675 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000676 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000677}
678
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000679StringRef AsmParser::ParseStringToEndOfStatement() {
680 const char *Start = getTok().getLoc().getPointer();
681
682 while (Lexer.isNot(AsmToken::EndOfStatement) &&
683 Lexer.isNot(AsmToken::Eof))
684 Lex();
685
686 const char *End = getTok().getLoc().getPointer();
687 return StringRef(Start, End - Start);
688}
Chris Lattnerc4193832009-06-22 05:51:26 +0000689
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000690StringRef AsmParser::ParseStringToComma() {
691 const char *Start = getTok().getLoc().getPointer();
692
693 while (Lexer.isNot(AsmToken::EndOfStatement) &&
694 Lexer.isNot(AsmToken::Comma) &&
695 Lexer.isNot(AsmToken::Eof))
696 Lex();
697
698 const char *End = getTok().getLoc().getPointer();
699 return StringRef(Start, End - Start);
700}
701
Chris Lattner74ec1a32009-06-22 06:32:03 +0000702/// ParseParenExpr - Parse a paren expression and return it.
703/// NOTE: This assumes the leading '(' has already been consumed.
704///
705/// parenexpr ::= expr)
706///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000707bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000708 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000709 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000711 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000712 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000713 return false;
714}
Chris Lattnerc4193832009-06-22 05:51:26 +0000715
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000716/// ParseBracketExpr - Parse a bracket expression and return it.
717/// NOTE: This assumes the leading '[' has already been consumed.
718///
719/// bracketexpr ::= expr]
720///
721bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
722 if (ParseExpression(Res)) return true;
723 if (Lexer.isNot(AsmToken::RBrac))
724 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000725 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000726 Lex();
727 return false;
728}
729
Chris Lattner74ec1a32009-06-22 06:32:03 +0000730/// ParsePrimaryExpr - Parse a primary expression and return it.
731/// primaryexpr ::= (parenexpr
732/// primaryexpr ::= symbol
733/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000734/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000735/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000736bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000737 SMLoc FirstTokenLoc = getLexer().getLoc();
738 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
739 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000740 default:
741 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000742 // If we have an error assume that we've already handled it.
743 case AsmToken::Error:
744 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000745 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000746 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000747 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000748 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000749 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000750 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000751 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000752 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000753 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000754 StringRef Identifier;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000755 if (ParseIdentifier(Identifier)) {
756 if (FirstTokenKind == AsmToken::Dollar)
757 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000758 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000759 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000760
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000761 EndLoc = SMLoc::getFromPointer(Identifier.end());
762
Daniel Dunbarfffff912009-10-16 01:34:54 +0000763 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000764 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000765 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000766
767 // Lookup the symbol variant if used.
768 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000769 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000770 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000771 if (Variant == MCSymbolRefExpr::VK_Invalid) {
772 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000773 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000774 }
775 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000776
Daniel Dunbarfffff912009-10-16 01:34:54 +0000777 // If this is an absolute variable reference, substitute it now to preserve
778 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000779 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000780 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000781 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000782
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000783 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000784 return false;
785 }
786
787 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000788 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000789 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000790 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000791 case AsmToken::Integer: {
792 SMLoc Loc = getTok().getLoc();
793 int64_t IntVal = getTok().getIntVal();
794 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000795 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000796 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000797 // Look for 'b' or 'f' following an Integer as a directional label
798 if (Lexer.getKind() == AsmToken::Identifier) {
799 StringRef IDVal = getTok().getString();
800 if (IDVal == "f" || IDVal == "b"){
801 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
802 IDVal == "f" ? 1 : 0);
803 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
804 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000805 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000806 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000807 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000808 Lex(); // Eat identifier.
809 }
810 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000811 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000812 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000813 case AsmToken::Real: {
814 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000815 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000816 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000817 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000818 Lex(); // Eat token.
819 return false;
820 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000821 case AsmToken::Dot: {
822 // This is a '.' reference, which references the current PC. Emit a
823 // temporary label to the streamer and refer to it.
824 MCSymbol *Sym = Ctx.CreateTempSymbol();
825 Out.EmitLabel(Sym);
826 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000827 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000828 Lex(); // Eat identifier.
829 return false;
830 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000831 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000832 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000833 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000834 case AsmToken::LBrac:
835 if (!PlatformParser->HasBracketExpressions())
836 return TokError("brackets expression not supported on this target");
837 Lex(); // Eat the '['.
838 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000839 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000840 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000841 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000842 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000843 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000844 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000845 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000846 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000847 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000848 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000849 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000851 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000852 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000853 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000854 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000855 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000857 }
858}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000859
Chris Lattnerb4307b32010-01-15 19:28:38 +0000860bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000861 SMLoc EndLoc;
862 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000863}
864
Daniel Dunbarcceba832010-09-17 02:47:07 +0000865const MCExpr *
866AsmParser::ApplyModifierToExpr(const MCExpr *E,
867 MCSymbolRefExpr::VariantKind Variant) {
868 // Recurse over the given expression, rebuilding it to apply the given variant
869 // if there is exactly one symbol.
870 switch (E->getKind()) {
871 case MCExpr::Target:
872 case MCExpr::Constant:
873 return 0;
874
875 case MCExpr::SymbolRef: {
876 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
877
878 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
879 TokError("invalid variant on expression '" +
880 getTok().getIdentifier() + "' (already modified)");
881 return E;
882 }
883
884 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
885 }
886
887 case MCExpr::Unary: {
888 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
889 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
890 if (!Sub)
891 return 0;
892 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
893 }
894
895 case MCExpr::Binary: {
896 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
897 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
898 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
899
900 if (!LHS && !RHS)
901 return 0;
902
903 if (!LHS) LHS = BE->getLHS();
904 if (!RHS) RHS = BE->getRHS();
905
906 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
907 }
908 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000909
Craig Topper85814382012-02-07 05:05:23 +0000910 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000911}
912
Chris Lattner74ec1a32009-06-22 06:32:03 +0000913/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000914///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000915/// expr ::= expr &&,|| expr -> lowest.
916/// expr ::= expr |,^,&,! expr
917/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
918/// expr ::= expr <<,>> expr
919/// expr ::= expr +,- expr
920/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000921/// expr ::= primaryexpr
922///
Chris Lattner54482b42010-01-15 19:39:23 +0000923bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000924 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000925 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000926 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
927 return true;
928
Daniel Dunbarcceba832010-09-17 02:47:07 +0000929 // As a special case, we support 'a op b @ modifier' by rewriting the
930 // expression to include the modifier. This is inefficient, but in general we
931 // expect users to use 'a@modifier op b'.
932 if (Lexer.getKind() == AsmToken::At) {
933 Lex();
934
935 if (Lexer.isNot(AsmToken::Identifier))
936 return TokError("unexpected symbol modifier following '@'");
937
938 MCSymbolRefExpr::VariantKind Variant =
939 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
940 if (Variant == MCSymbolRefExpr::VK_Invalid)
941 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
942
943 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
944 if (!ModifiedRes) {
945 return TokError("invalid modifier '" + getTok().getIdentifier() +
946 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000947 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000948
Daniel Dunbarcceba832010-09-17 02:47:07 +0000949 Res = ModifiedRes;
950 Lex();
951 }
952
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000953 // Try to constant fold it up front, if possible.
954 int64_t Value;
955 if (Res->EvaluateAsAbsolute(Value))
956 Res = MCConstantExpr::Create(Value, getContext());
957
958 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000959}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000960
Chris Lattnerb4307b32010-01-15 19:28:38 +0000961bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000962 Res = 0;
963 return ParseParenExpr(Res, EndLoc) ||
964 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000965}
966
Daniel Dunbar475839e2009-06-29 20:37:27 +0000967bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000968 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000969
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000970 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000971 if (ParseExpression(Expr))
972 return true;
973
Daniel Dunbare00b0112009-10-16 01:57:52 +0000974 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000975 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000976
977 return false;
978}
979
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000980static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000981 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000982 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000983 default:
984 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000985
Jim Grosbachfbe16812011-08-20 16:24:13 +0000986 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000987 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000988 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000989 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000990 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000991 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000992 return 1;
993
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000994
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000995 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000996 //
997 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000998 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000999 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001000 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001001 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001002 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001003 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001004 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001005 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001006 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001007
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001008 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001009 case AsmToken::EqualEqual:
1010 Kind = MCBinaryExpr::EQ;
1011 return 3;
1012 case AsmToken::ExclaimEqual:
1013 case AsmToken::LessGreater:
1014 Kind = MCBinaryExpr::NE;
1015 return 3;
1016 case AsmToken::Less:
1017 Kind = MCBinaryExpr::LT;
1018 return 3;
1019 case AsmToken::LessEqual:
1020 Kind = MCBinaryExpr::LTE;
1021 return 3;
1022 case AsmToken::Greater:
1023 Kind = MCBinaryExpr::GT;
1024 return 3;
1025 case AsmToken::GreaterEqual:
1026 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001027 return 3;
1028
Jim Grosbachfbe16812011-08-20 16:24:13 +00001029 // Intermediate Precedence: <<, >>
1030 case AsmToken::LessLess:
1031 Kind = MCBinaryExpr::Shl;
1032 return 4;
1033 case AsmToken::GreaterGreater:
1034 Kind = MCBinaryExpr::Shr;
1035 return 4;
1036
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001037 // High Intermediate Precedence: +, -
1038 case AsmToken::Plus:
1039 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001040 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001041 case AsmToken::Minus:
1042 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001043 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001044
Jim Grosbachfbe16812011-08-20 16:24:13 +00001045 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001046 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001047 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001048 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001049 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001050 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001051 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001052 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001053 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001054 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001055 }
1056}
1057
1058
1059/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1060/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001061bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1062 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001063 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001064 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001065 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001066
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001067 // If the next token is lower precedence than we are allowed to eat, return
1068 // successfully with what we ate already.
1069 if (TokPrec < Precedence)
1070 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001071
Sean Callanan79ed1a82010-01-19 20:22:31 +00001072 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001073
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001075 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001076 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001077
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001078 // If BinOp binds less tightly with RHS than the operator after RHS, let
1079 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001080 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001081 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001082 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001083 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 }
1085
Daniel Dunbar475839e2009-06-29 20:37:27 +00001086 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001087 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001088 }
1089}
1090
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001091/// ParseStatement:
1092/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001093/// ::= Label* Directive ...Operands... EndOfStatement
1094/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001095bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001096 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001097 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001098 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001099 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001100 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001101
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001102 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001103 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001104 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001105 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001106 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001107 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001108 if (Lexer.is(AsmToken::Hash))
1109 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001110
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001111 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001112 if (Lexer.is(AsmToken::Integer)) {
1113 LocalLabelVal = getTok().getIntVal();
1114 if (LocalLabelVal < 0) {
1115 if (!TheCondState.Ignore)
1116 return TokError("unexpected token at start of statement");
1117 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001118 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001119 IDVal = getTok().getString();
1120 Lex(); // Consume the integer token to be used as an identifier token.
1121 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001122 if (!TheCondState.Ignore)
1123 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001124 }
1125 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001126 } else if (Lexer.is(AsmToken::Dot)) {
1127 // Treat '.' as a valid identifier in this context.
1128 Lex();
1129 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001130 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001131 if (!TheCondState.Ignore)
1132 return TokError("unexpected token at start of statement");
1133 IDVal = "";
1134 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001135
Chris Lattner7834fac2010-04-17 18:14:27 +00001136 // Handle conditional assembly here before checking for skipping. We
1137 // have to do this so that .endif isn't skipped in a ".if 0" block for
1138 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001139 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001140 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001141 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001142 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1143 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001144 switch (DirKind) {
1145 default:
1146 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001147 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001148 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001149 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001150 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001151 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001152 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001153 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001154 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001155 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001157 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001158 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001159 case DK_IFNDEF:
1160 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001161 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001162 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001163 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001164 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001165 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001166 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001167 return ParseDirectiveEndIf(IDLoc);
1168 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001169
Eli Benderskyed5df012013-01-16 19:32:36 +00001170 // Ignore the statement if in the middle of inactive conditional
1171 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001172 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001173 EatToEndOfStatement();
1174 return false;
1175 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001176
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001177 // FIXME: Recurse on local labels?
1178
1179 // See what kind of statement we have.
1180 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001181 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001182 CheckForValidSection();
1183
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001184 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001185 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001186
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001187 // Diagnose attempt to use '.' as a label.
1188 if (IDVal == ".")
1189 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1190
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001191 // Diagnose attempt to use a variable as a label.
1192 //
1193 // FIXME: Diagnostics. Note the location of the definition as a label.
1194 // FIXME: This doesn't diagnose assignment to a symbol which has been
1195 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001196 MCSymbol *Sym;
1197 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001198 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001199 else
1200 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001201 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001202 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001203
Daniel Dunbar959fd882009-08-26 22:13:22 +00001204 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001205 if (!ParsingInlineAsm)
1206 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001207
Kevin Enderby94c2e852011-12-09 18:09:40 +00001208 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001209 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001210 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001211 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1212 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001213
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001214 // Consume any end of statement token, if present, to avoid spurious
1215 // AddBlankLine calls().
1216 if (Lexer.is(AsmToken::EndOfStatement)) {
1217 Lex();
1218 if (Lexer.is(AsmToken::Eof))
1219 return false;
1220 }
1221
Eli Friedman2128aae2012-10-22 23:58:19 +00001222 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001223 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001224
Daniel Dunbar3f872332009-07-28 16:08:33 +00001225 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001226 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001227 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228
Nico Weber4c4c7322011-01-28 03:04:41 +00001229 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001230
1231 default: // Normal instruction or directive.
1232 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001233 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001234
1235 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001236 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001237 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1238 return HandleMacroEntry(M, IDLoc);
1239 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001240
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001241 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001242
1243 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001244 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001245 // There are several entities interested in parsing directives:
1246 //
1247 // 1. The target-specific assembly parser. Some directives are target
1248 // specific or may potentially behave differently on certain targets.
1249 // 2. Asm parser extensions. For example, platform-specific parsers
1250 // (like the ELF parser) register themselves as extensions.
1251 // 3. The generic directive parser implemented by this class. These are
1252 // all the directives that behave in a target and platform independent
1253 // manner, or at least have a default behavior that's shared between
1254 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001255
Eli Bendersky6ee13082013-01-15 22:59:42 +00001256 // First query the target-specific parser. It will return 'true' if it
1257 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001258 if (!getTargetParser().ParseDirective(ID))
1259 return false;
1260
Eli Bendersky6ee13082013-01-15 22:59:42 +00001261 // Next, check the extention directive map to see if any extension has
1262 // registered itself to parse this directive.
1263 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1264 ExtensionDirectiveMap.lookup(IDVal);
1265 if (Handler.first)
1266 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1267
1268 // Finally, if no one else is interested in this directive, it must be
1269 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001270 switch (DirKind) {
1271 default:
1272 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001273 case DK_SET:
1274 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001275 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001276 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001278 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001279 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_ASCIZ:
1281 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001284 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_SHORT:
1286 case DK_VALUE:
1287 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001288 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001289 case DK_LONG:
1290 case DK_INT:
1291 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001292 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001293 case DK_QUAD:
1294 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_SINGLE:
1297 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001299 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001302 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1303 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1304 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1307 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1308 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001309 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001319 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 EatToEndOfStatement(); // .extern is the default, ignore it.
1329 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_GLOBL:
1331 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_COMM:
1352 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_CODE16:
1363 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001374 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001375 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001379 case DK_SLEB128:
1380 return ParseDirectiveLEB128(true);
1381 case DK_ULEB128:
1382 return ParseDirectiveLEB128(false);
1383 case DK_SPACE:
1384 case DK_SKIP:
1385 return ParseDirectiveSpace(IDVal);
1386 case DK_FILE:
1387 return ParseDirectiveFile(IDLoc);
1388 case DK_LINE:
1389 return ParseDirectiveLine();
1390 case DK_LOC:
1391 return ParseDirectiveLoc();
1392 case DK_STABS:
1393 return ParseDirectiveStabs();
1394 case DK_CFI_SECTIONS:
1395 return ParseDirectiveCFISections();
1396 case DK_CFI_STARTPROC:
1397 return ParseDirectiveCFIStartProc();
1398 case DK_CFI_ENDPROC:
1399 return ParseDirectiveCFIEndProc();
1400 case DK_CFI_DEF_CFA:
1401 return ParseDirectiveCFIDefCfa(IDLoc);
1402 case DK_CFI_DEF_CFA_OFFSET:
1403 return ParseDirectiveCFIDefCfaOffset();
1404 case DK_CFI_ADJUST_CFA_OFFSET:
1405 return ParseDirectiveCFIAdjustCfaOffset();
1406 case DK_CFI_DEF_CFA_REGISTER:
1407 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1408 case DK_CFI_OFFSET:
1409 return ParseDirectiveCFIOffset(IDLoc);
1410 case DK_CFI_REL_OFFSET:
1411 return ParseDirectiveCFIRelOffset(IDLoc);
1412 case DK_CFI_PERSONALITY:
1413 return ParseDirectiveCFIPersonalityOrLsda(true);
1414 case DK_CFI_LSDA:
1415 return ParseDirectiveCFIPersonalityOrLsda(false);
1416 case DK_CFI_REMEMBER_STATE:
1417 return ParseDirectiveCFIRememberState();
1418 case DK_CFI_RESTORE_STATE:
1419 return ParseDirectiveCFIRestoreState();
1420 case DK_CFI_SAME_VALUE:
1421 return ParseDirectiveCFISameValue(IDLoc);
1422 case DK_CFI_RESTORE:
1423 return ParseDirectiveCFIRestore(IDLoc);
1424 case DK_CFI_ESCAPE:
1425 return ParseDirectiveCFIEscape();
1426 case DK_CFI_SIGNAL_FRAME:
1427 return ParseDirectiveCFISignalFrame();
1428 case DK_CFI_UNDEFINED:
1429 return ParseDirectiveCFIUndefined(IDLoc);
1430 case DK_CFI_REGISTER:
1431 return ParseDirectiveCFIRegister(IDLoc);
1432 case DK_MACROS_ON:
1433 case DK_MACROS_OFF:
1434 return ParseDirectiveMacrosOnOff(IDVal);
1435 case DK_MACRO:
1436 return ParseDirectiveMacro(IDLoc);
1437 case DK_ENDM:
1438 case DK_ENDMACRO:
1439 return ParseDirectiveEndMacro(IDVal);
1440 case DK_PURGEM:
1441 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001442 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001443
Jim Grosbach686c0182012-05-01 18:38:27 +00001444 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001445 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001446
Eli Friedman2128aae2012-10-22 23:58:19 +00001447 // _emit
1448 if (ParsingInlineAsm && IDVal == "_emit")
1449 return ParseDirectiveEmit(IDLoc, Info);
1450
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001451 CheckForValidSection();
1452
Chris Lattnera7f13542010-05-19 23:34:33 +00001453 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001454 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001455 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001456 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1457 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001458 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001459
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001460 // Dump the parsed representation, if requested.
1461 if (getShowParsedOperands()) {
1462 SmallString<256> Str;
1463 raw_svector_ostream OS(Str);
1464 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001465 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001466 if (i != 0)
1467 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001468 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001469 }
1470 OS << "]";
1471
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001472 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001473 }
1474
Kevin Enderby613b7572011-11-01 22:27:22 +00001475 // If we are generating dwarf for assembly source files and the current
1476 // section is the initial text section then generate a .loc directive for
1477 // the instruction.
1478 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001479 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001480
Eli Benderskyed5df012013-01-16 19:32:36 +00001481 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001482
Eli Benderskyed5df012013-01-16 19:32:36 +00001483 // If we previously parsed a cpp hash file line comment then make sure the
1484 // current Dwarf File is for the CppHashFilename if not then emit the
1485 // Dwarf File table for it and adjust the line number for the .loc.
1486 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1487 getContext().getMCDwarfFiles();
1488 if (CppHashFilename.size() != 0) {
1489 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001490 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001491 getStreamer().EmitDwarfFileDirective(
1492 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001493
Kevin Enderby32c1a822012-11-05 21:55:41 +00001494 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001495 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001496 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001497
Kevin Enderby613b7572011-11-01 22:27:22 +00001498 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001499 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001500 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001501 StringRef());
1502 }
1503
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001504 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001505 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001506 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001507 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1508 Info.ParsedOperands,
1509 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001510 ParsingInlineAsm);
1511 }
Chris Lattner98986712010-01-14 22:21:20 +00001512
Chris Lattnercbf8a982010-09-11 16:18:25 +00001513 // Don't skip the rest of the line, the instruction parser is responsible for
1514 // that.
1515 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001516}
Chris Lattner9a023f72009-06-24 04:43:34 +00001517
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001518/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1519/// since they may not be able to be tokenized to get to the end of line token.
1520void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001521 if (!Lexer.is(AsmToken::EndOfStatement))
1522 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001523 // Eat EOL.
1524 Lex();
1525}
1526
1527/// ParseCppHashLineFilenameComment as this:
1528/// ::= # number "filename"
1529/// or just as a full line comment if it doesn't have a number and a string.
1530bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1531 Lex(); // Eat the hash token.
1532
1533 if (getLexer().isNot(AsmToken::Integer)) {
1534 // Consume the line since in cases it is not a well-formed line directive,
1535 // as if were simply a full line comment.
1536 EatToEndOfLine();
1537 return false;
1538 }
1539
1540 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001541 Lex();
1542
1543 if (getLexer().isNot(AsmToken::String)) {
1544 EatToEndOfLine();
1545 return false;
1546 }
1547
1548 StringRef Filename = getTok().getString();
1549 // Get rid of the enclosing quotes.
1550 Filename = Filename.substr(1, Filename.size()-2);
1551
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001552 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1553 CppHashLoc = L;
1554 CppHashFilename = Filename;
1555 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001556 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001557
1558 // Ignore any trailing characters, they're just comment.
1559 EatToEndOfLine();
1560 return false;
1561}
1562
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001563/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001564/// for the Filename and LineNo if any in the diagnostic.
1565void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1566 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1567 raw_ostream &OS = errs();
1568
1569 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1570 const SMLoc &DiagLoc = Diag.getLoc();
1571 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1572 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1573
1574 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1575 // before printing the message.
1576 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001577 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001578 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1579 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1580 }
1581
Eric Christopher2318ba12012-12-18 00:30:54 +00001582 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001583 // manager changed or buffer changed (like in a nested include) then just
1584 // print the normal diagnostic using its Filename and LineNo.
1585 if (!Parser->CppHashLineNumber ||
1586 &DiagSrcMgr != &Parser->SrcMgr ||
1587 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001588 if (Parser->SavedDiagHandler)
1589 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1590 else
1591 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001592 return;
1593 }
1594
Eric Christopher2318ba12012-12-18 00:30:54 +00001595 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001596 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1597 // the diagnostic.
1598 const std::string Filename = Parser->CppHashFilename;
1599
1600 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1601 int CppHashLocLineNo =
1602 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1603 int LineNo = Parser->CppHashLineNumber - 1 +
1604 (DiagLocLineNo - CppHashLocLineNo);
1605
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001606 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1607 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001608 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001609 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001610
Benjamin Kramer04a04262011-10-16 10:48:29 +00001611 if (Parser->SavedDiagHandler)
1612 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1613 else
1614 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001615}
1616
Rafael Espindola799aacf2012-08-21 18:29:30 +00001617// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1618// difference being that that function accepts '@' as part of identifiers and
1619// we can't do that. AsmLexer.cpp should probably be changed to handle
1620// '@' as a special case when needed.
1621static bool isIdentifierChar(char c) {
1622 return isalnum(c) || c == '_' || c == '$' || c == '.';
1623}
1624
Rafael Espindola761cb062012-06-03 23:57:14 +00001625bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001626 const MCAsmMacroParameters &Parameters,
1627 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001628 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001629 unsigned NParameters = Parameters.size();
1630 if (NParameters != 0 && NParameters != A.size())
1631 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001632
Preston Gurd7b6f2032012-09-19 20:36:12 +00001633 // A macro without parameters is handled differently on Darwin:
1634 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001635 while (!Body.empty()) {
1636 // Scan for the next substitution.
1637 std::size_t End = Body.size(), Pos = 0;
1638 for (; Pos != End; ++Pos) {
1639 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001640 if (!NParameters) {
1641 // This macro has no parameters, look for $0, $1, etc.
1642 if (Body[Pos] != '$' || Pos + 1 == End)
1643 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001644
Rafael Espindola65366442011-06-05 02:43:45 +00001645 char Next = Body[Pos + 1];
1646 if (Next == '$' || Next == 'n' || isdigit(Next))
1647 break;
1648 } else {
1649 // This macro has parameters, look for \foo, \bar, etc.
1650 if (Body[Pos] == '\\' && Pos + 1 != End)
1651 break;
1652 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001653 }
1654
1655 // Add the prefix.
1656 OS << Body.slice(0, Pos);
1657
1658 // Check if we reached the end.
1659 if (Pos == End)
1660 break;
1661
Rafael Espindola65366442011-06-05 02:43:45 +00001662 if (!NParameters) {
1663 switch (Body[Pos+1]) {
1664 // $$ => $
1665 case '$':
1666 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001667 break;
1668
Rafael Espindola65366442011-06-05 02:43:45 +00001669 // $n => number of arguments
1670 case 'n':
1671 OS << A.size();
1672 break;
1673
1674 // $[0-9] => argument
1675 default: {
1676 // Missing arguments are ignored.
1677 unsigned Index = Body[Pos+1] - '0';
1678 if (Index >= A.size())
1679 break;
1680
1681 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001682 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001683 ie = A[Index].end(); it != ie; ++it)
1684 OS << it->getString();
1685 break;
1686 }
1687 }
1688 Pos += 2;
1689 } else {
1690 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001691 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001692 ++I;
1693
1694 const char *Begin = Body.data() + Pos +1;
1695 StringRef Argument(Begin, I - (Pos +1));
1696 unsigned Index = 0;
1697 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001698 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001699 break;
1700
Preston Gurd7b6f2032012-09-19 20:36:12 +00001701 if (Index == NParameters) {
1702 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1703 Pos += 3;
1704 else {
1705 OS << '\\' << Argument;
1706 Pos = I;
1707 }
1708 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001709 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001710 ie = A[Index].end(); it != ie; ++it)
1711 if (it->getKind() == AsmToken::String)
1712 OS << it->getStringContents();
1713 else
1714 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001715
Preston Gurd7b6f2032012-09-19 20:36:12 +00001716 Pos += 1 + Argument.size();
1717 }
Rafael Espindola65366442011-06-05 02:43:45 +00001718 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001719 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001720 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001721 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001722
Rafael Espindola65366442011-06-05 02:43:45 +00001723 return false;
1724}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001725
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001726MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001727 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001728 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001729 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1730 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001731{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001732}
1733
Preston Gurd7b6f2032012-09-19 20:36:12 +00001734static bool IsOperator(AsmToken::TokenKind kind)
1735{
1736 switch (kind)
1737 {
1738 default:
1739 return false;
1740 case AsmToken::Plus:
1741 case AsmToken::Minus:
1742 case AsmToken::Tilde:
1743 case AsmToken::Slash:
1744 case AsmToken::Star:
1745 case AsmToken::Dot:
1746 case AsmToken::Equal:
1747 case AsmToken::EqualEqual:
1748 case AsmToken::Pipe:
1749 case AsmToken::PipePipe:
1750 case AsmToken::Caret:
1751 case AsmToken::Amp:
1752 case AsmToken::AmpAmp:
1753 case AsmToken::Exclaim:
1754 case AsmToken::ExclaimEqual:
1755 case AsmToken::Percent:
1756 case AsmToken::Less:
1757 case AsmToken::LessEqual:
1758 case AsmToken::LessLess:
1759 case AsmToken::LessGreater:
1760 case AsmToken::Greater:
1761 case AsmToken::GreaterEqual:
1762 case AsmToken::GreaterGreater:
1763 return true;
1764 }
1765}
1766
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001767bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001768 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001769 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001770 unsigned AddTokens = 0;
1771
1772 // gas accepts arguments separated by whitespace, except on Darwin
1773 if (!IsDarwin)
1774 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001775
1776 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001777 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1778 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001779 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001780 }
1781
1782 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1783 // Spaces and commas cannot be mixed to delimit parameters
1784 if (ArgumentDelimiter == AsmToken::Eof)
1785 ArgumentDelimiter = AsmToken::Comma;
1786 else if (ArgumentDelimiter != AsmToken::Comma) {
1787 Lexer.setSkipSpace(true);
1788 return TokError("expected ' ' for macro argument separator");
1789 }
1790 break;
1791 }
1792
1793 if (Lexer.is(AsmToken::Space)) {
1794 Lex(); // Eat spaces
1795
1796 // Spaces can delimit parameters, but could also be part an expression.
1797 // If the token after a space is an operator, add the token and the next
1798 // one into this argument
1799 if (ArgumentDelimiter == AsmToken::Space ||
1800 ArgumentDelimiter == AsmToken::Eof) {
1801 if (IsOperator(Lexer.getKind())) {
1802 // Check to see whether the token is used as an operator,
1803 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001804 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001805 if (*NextChar == ' ')
1806 AddTokens = 2;
1807 }
1808
1809 if (!AddTokens && ParenLevel == 0) {
1810 if (ArgumentDelimiter == AsmToken::Eof &&
1811 !IsOperator(Lexer.getKind()))
1812 ArgumentDelimiter = AsmToken::Space;
1813 break;
1814 }
1815 }
1816 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001817
1818 // HandleMacroEntry relies on not advancing the lexer here
1819 // to be able to fill in the remaining default parameter values
1820 if (Lexer.is(AsmToken::EndOfStatement))
1821 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001822
1823 // Adjust the current parentheses level.
1824 if (Lexer.is(AsmToken::LParen))
1825 ++ParenLevel;
1826 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1827 --ParenLevel;
1828
1829 // Append the token to the current argument list.
1830 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001831 if (AddTokens)
1832 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001833 Lex();
1834 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001835
1836 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001837 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001838 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001839 return false;
1840}
1841
1842// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001843bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001844 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001845 // Argument delimiter is initially unknown. It will be set by
1846 // ParseMacroArgument()
1847 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001848
1849 // Parse two kinds of macro invocations:
1850 // - macros defined without any parameters accept an arbitrary number of them
1851 // - macros defined with parameters accept at most that many of them
1852 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1853 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001854 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001855
Preston Gurd7b6f2032012-09-19 20:36:12 +00001856 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001857 return true;
1858
Preston Gurd6c9176a2012-09-19 20:29:04 +00001859 if (!MA.empty() || !NParameters)
1860 A.push_back(MA);
1861 else if (NParameters) {
1862 if (!M->Parameters[Parameter].second.empty())
1863 A.push_back(M->Parameters[Parameter].second);
1864 }
Jim Grosbach97146442012-07-30 22:44:17 +00001865
Preston Gurd6c9176a2012-09-19 20:29:04 +00001866 // At the end of the statement, fill in remaining arguments that have
1867 // default values. If there aren't any, then the next argument is
1868 // required but missing
1869 if (Lexer.is(AsmToken::EndOfStatement)) {
1870 if (NParameters && Parameter < NParameters - 1) {
1871 if (M->Parameters[Parameter + 1].second.empty())
1872 return TokError("macro argument '" +
1873 Twine(M->Parameters[Parameter + 1].first) +
1874 "' is missing");
1875 else
1876 continue;
1877 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001878 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001879 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001880
1881 if (Lexer.is(AsmToken::Comma))
1882 Lex();
1883 }
1884 return TokError("Too many arguments");
1885}
1886
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001887const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1888 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1889 return (I == MacroMap.end()) ? NULL : I->getValue();
1890}
1891
1892void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1893 MacroMap[Name] = new MCAsmMacro(Macro);
1894}
1895
1896void AsmParser::UndefineMacro(StringRef Name) {
1897 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1898 if (I != MacroMap.end()) {
1899 delete I->getValue();
1900 MacroMap.erase(I);
1901 }
1902}
1903
1904bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001905 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1906 // this, although we should protect against infinite loops.
1907 if (ActiveMacros.size() == 20)
1908 return TokError("macros cannot be nested more than 20 levels deep");
1909
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001910 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001911 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001912 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001913
Jim Grosbach97146442012-07-30 22:44:17 +00001914 // Remove any trailing empty arguments. Do this after-the-fact as we have
1915 // to keep empty arguments in the middle of the list or positionality
1916 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001917 while (!A.empty() && A.back().empty())
1918 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001919
Rafael Espindola65366442011-06-05 02:43:45 +00001920 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1921 // to hold the macro body with substitutions.
1922 SmallString<256> Buf;
1923 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001924 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001925
Rafael Espindola8a403d32012-08-08 14:51:03 +00001926 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001927 return true;
1928
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001929 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001930 // instantiation.
1931 OS << ".endmacro\n";
1932
Rafael Espindola65366442011-06-05 02:43:45 +00001933 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001934 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001935
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001936 // Create the macro instantiation object and add to the current macro
1937 // instantiation stack.
1938 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001939 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001940 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001941 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001942 ActiveMacros.push_back(MI);
1943
1944 // Jump to the macro instantiation and prime the lexer.
1945 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1946 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1947 Lex();
1948
1949 return false;
1950}
1951
1952void AsmParser::HandleMacroExit() {
1953 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001954 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001955 Lex();
1956
1957 // Pop the instantiation entry.
1958 delete ActiveMacros.back();
1959 ActiveMacros.pop_back();
1960}
1961
Rafael Espindolae71cc862012-01-28 05:57:00 +00001962static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001963 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001964 case MCExpr::Binary: {
1965 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1966 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001967 break;
1968 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001969 case MCExpr::Target:
1970 case MCExpr::Constant:
1971 return false;
1972 case MCExpr::SymbolRef: {
1973 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001974 if (S.isVariable())
1975 return IsUsedIn(Sym, S.getVariableValue());
1976 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001977 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001978 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001979 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001980 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001981
1982 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001983}
1984
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001985bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1986 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001987 // FIXME: Use better location, we should use proper tokens.
1988 SMLoc EqualLoc = Lexer.getLoc();
1989
Daniel Dunbar821e3332009-08-31 08:09:28 +00001990 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001991 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001992 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001993
Rafael Espindolae71cc862012-01-28 05:57:00 +00001994 // Note: we don't count b as used in "a = b". This is to allow
1995 // a = b
1996 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001997
Daniel Dunbar3f872332009-07-28 16:08:33 +00001998 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001999 return TokError("unexpected token in assignment");
2000
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002001 // Error on assignment to '.'.
2002 if (Name == ".") {
2003 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2004 "(use '.space' or '.org').)"));
2005 }
2006
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002007 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002008 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002009
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002010 // Validate that the LHS is allowed to be a variable (either it has not been
2011 // used as a symbol, or it is an absolute symbol).
2012 MCSymbol *Sym = getContext().LookupSymbol(Name);
2013 if (Sym) {
2014 // Diagnose assignment to a label.
2015 //
2016 // FIXME: Diagnostics. Note the location of the definition as a label.
2017 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002018 if (IsUsedIn(Sym, Value))
2019 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2020 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002021 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002022 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2023 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002024 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002025 return Error(EqualLoc, "redefinition of '" + Name + "'");
2026 else if (!Sym->isVariable())
2027 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002028 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002029 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2030 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002031
2032 // Don't count these checks as uses.
2033 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002034 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002035 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002036
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002037 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002038
2039 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002040 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002041 if (NoDeadStrip)
2042 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2043
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002044
2045 return false;
2046}
2047
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002048/// ParseIdentifier:
2049/// ::= identifier
2050/// ::= string
2051bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002052 // The assembler has relaxed rules for accepting identifiers, in particular we
2053 // allow things like '.globl $foo', which would normally be separate
2054 // tokens. At this level, we have already lexed so we cannot (currently)
2055 // handle this as a context dependent token, instead we detect adjacent tokens
2056 // and return the combined identifier.
2057 if (Lexer.is(AsmToken::Dollar)) {
2058 SMLoc DollarLoc = getLexer().getLoc();
2059
2060 // Consume the dollar sign, and check for a following identifier.
2061 Lex();
2062 if (Lexer.isNot(AsmToken::Identifier))
2063 return true;
2064
2065 // We have a '$' followed by an identifier, make sure they are adjacent.
2066 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2067 return true;
2068
2069 // Construct the joined identifier and consume the token.
2070 Res = StringRef(DollarLoc.getPointer(),
2071 getTok().getIdentifier().size() + 1);
2072 Lex();
2073 return false;
2074 }
2075
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002076 if (Lexer.isNot(AsmToken::Identifier) &&
2077 Lexer.isNot(AsmToken::String))
2078 return true;
2079
Sean Callanan18b83232010-01-19 21:44:56 +00002080 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002081
Sean Callanan79ed1a82010-01-19 20:22:31 +00002082 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002083
2084 return false;
2085}
2086
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002087/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002088/// ::= .equ identifier ',' expression
2089/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002090/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002091bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002092 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002093
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002094 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002095 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002096
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002097 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002098 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002099 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002100
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002101 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002102}
2103
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002104bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002105 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002106
2107 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002108 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002109 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2110 if (Str[i] != '\\') {
2111 Data += Str[i];
2112 continue;
2113 }
2114
2115 // Recognize escaped characters. Note that this escape semantics currently
2116 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2117 ++i;
2118 if (i == e)
2119 return TokError("unexpected backslash at end of string");
2120
2121 // Recognize octal sequences.
2122 if ((unsigned) (Str[i] - '0') <= 7) {
2123 // Consume up to three octal characters.
2124 unsigned Value = Str[i] - '0';
2125
2126 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2127 ++i;
2128 Value = Value * 8 + (Str[i] - '0');
2129
2130 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2131 ++i;
2132 Value = Value * 8 + (Str[i] - '0');
2133 }
2134 }
2135
2136 if (Value > 255)
2137 return TokError("invalid octal escape sequence (out of range)");
2138
2139 Data += (unsigned char) Value;
2140 continue;
2141 }
2142
2143 // Otherwise recognize individual escapes.
2144 switch (Str[i]) {
2145 default:
2146 // Just reject invalid escape sequences for now.
2147 return TokError("invalid escape sequence (unrecognized character)");
2148
2149 case 'b': Data += '\b'; break;
2150 case 'f': Data += '\f'; break;
2151 case 'n': Data += '\n'; break;
2152 case 'r': Data += '\r'; break;
2153 case 't': Data += '\t'; break;
2154 case '"': Data += '"'; break;
2155 case '\\': Data += '\\'; break;
2156 }
2157 }
2158
2159 return false;
2160}
2161
Daniel Dunbara0d14262009-06-24 23:30:00 +00002162/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002163/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2164bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002165 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002166 CheckForValidSection();
2167
Daniel Dunbara0d14262009-06-24 23:30:00 +00002168 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002169 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002170 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002171
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002172 std::string Data;
2173 if (ParseEscapedString(Data))
2174 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002175
2176 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002177 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002178 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2179
Sean Callanan79ed1a82010-01-19 20:22:31 +00002180 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002181
2182 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002183 break;
2184
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002185 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002186 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002187 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002188 }
2189 }
2190
Sean Callanan79ed1a82010-01-19 20:22:31 +00002191 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002192 return false;
2193}
2194
2195/// ParseDirectiveValue
2196/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2197bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002198 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002199 CheckForValidSection();
2200
Daniel Dunbara0d14262009-06-24 23:30:00 +00002201 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002202 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002203 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002204 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002205 return true;
2206
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002207 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002208 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2209 assert(Size <= 8 && "Invalid size");
2210 uint64_t IntValue = MCE->getValue();
2211 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2212 return Error(ExprLoc, "literal value out of range for directive");
2213 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2214 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002216
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002219
Daniel Dunbara0d14262009-06-24 23:30:00 +00002220 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002222 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002223 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 }
2225 }
2226
Sean Callanan79ed1a82010-01-19 20:22:31 +00002227 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002228 return false;
2229}
2230
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002231/// ParseDirectiveRealValue
2232/// ::= (.single | .double) [ expression (, expression)* ]
2233bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2234 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2235 CheckForValidSection();
2236
2237 for (;;) {
2238 // We don't truly support arithmetic on floating point expressions, so we
2239 // have to manually parse unary prefixes.
2240 bool IsNeg = false;
2241 if (getLexer().is(AsmToken::Minus)) {
2242 Lex();
2243 IsNeg = true;
2244 } else if (getLexer().is(AsmToken::Plus))
2245 Lex();
2246
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002247 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002248 getLexer().isNot(AsmToken::Real) &&
2249 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002250 return TokError("unexpected token in directive");
2251
2252 // Convert to an APFloat.
2253 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002254 StringRef IDVal = getTok().getString();
2255 if (getLexer().is(AsmToken::Identifier)) {
2256 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2257 Value = APFloat::getInf(Semantics);
2258 else if (!IDVal.compare_lower("nan"))
2259 Value = APFloat::getNaN(Semantics, false, ~0);
2260 else
2261 return TokError("invalid floating point literal");
2262 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002263 APFloat::opInvalidOp)
2264 return TokError("invalid floating point literal");
2265 if (IsNeg)
2266 Value.changeSign();
2267
2268 // Consume the numeric token.
2269 Lex();
2270
2271 // Emit the value as an integer.
2272 APInt AsInt = Value.bitcastToAPInt();
2273 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2274 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2275
2276 if (getLexer().is(AsmToken::EndOfStatement))
2277 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002278
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002279 if (getLexer().isNot(AsmToken::Comma))
2280 return TokError("unexpected token in directive");
2281 Lex();
2282 }
2283 }
2284
2285 Lex();
2286 return false;
2287}
2288
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002289/// ParseDirectiveZero
2290/// ::= .zero expression
2291bool AsmParser::ParseDirectiveZero() {
2292 CheckForValidSection();
2293
2294 int64_t NumBytes;
2295 if (ParseAbsoluteExpression(NumBytes))
2296 return true;
2297
Rafael Espindolae452b172010-10-05 19:42:57 +00002298 int64_t Val = 0;
2299 if (getLexer().is(AsmToken::Comma)) {
2300 Lex();
2301 if (ParseAbsoluteExpression(Val))
2302 return true;
2303 }
2304
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002305 if (getLexer().isNot(AsmToken::EndOfStatement))
2306 return TokError("unexpected token in '.zero' directive");
2307
2308 Lex();
2309
Rafael Espindolae452b172010-10-05 19:42:57 +00002310 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002311
2312 return false;
2313}
2314
Daniel Dunbara0d14262009-06-24 23:30:00 +00002315/// ParseDirectiveFill
2316/// ::= .fill expression , expression , expression
2317bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002318 CheckForValidSection();
2319
Daniel Dunbara0d14262009-06-24 23:30:00 +00002320 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002321 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002322 return true;
2323
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002324 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002325 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002326 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002327
Daniel Dunbara0d14262009-06-24 23:30:00 +00002328 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002329 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002330 return true;
2331
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002332 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002333 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002334 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002335
Daniel Dunbara0d14262009-06-24 23:30:00 +00002336 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002337 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002338 return true;
2339
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002340 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002341 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002342
Sean Callanan79ed1a82010-01-19 20:22:31 +00002343 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002344
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002345 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2346 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002347
2348 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002349 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002350
2351 return false;
2352}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002353
2354/// ParseDirectiveOrg
2355/// ::= .org expression [ , expression ]
2356bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002357 CheckForValidSection();
2358
Daniel Dunbar821e3332009-08-31 08:09:28 +00002359 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002360 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002361 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002362 return true;
2363
2364 // Parse optional fill expression.
2365 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002366 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2367 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002368 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002369 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002370
Daniel Dunbar475839e2009-06-29 20:37:27 +00002371 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002372 return true;
2373
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002374 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002375 return TokError("unexpected token in '.org' directive");
2376 }
2377
Sean Callanan79ed1a82010-01-19 20:22:31 +00002378 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002379
Jim Grosbachebd4c052012-01-27 00:37:08 +00002380 // Only limited forms of relocatable expressions are accepted here, it
2381 // has to be relative to the current section. The streamer will return
2382 // 'true' if the expression wasn't evaluatable.
2383 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2384 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002385
2386 return false;
2387}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002388
2389/// ParseDirectiveAlign
2390/// ::= {.align, ...} expression [ , expression [ , expression ]]
2391bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002392 CheckForValidSection();
2393
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002394 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002395 int64_t Alignment;
2396 if (ParseAbsoluteExpression(Alignment))
2397 return true;
2398
2399 SMLoc MaxBytesLoc;
2400 bool HasFillExpr = false;
2401 int64_t FillExpr = 0;
2402 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002403 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2404 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002405 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002406 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002407
2408 // The fill expression can be omitted while specifying a maximum number of
2409 // alignment bytes, e.g:
2410 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002411 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002412 HasFillExpr = true;
2413 if (ParseAbsoluteExpression(FillExpr))
2414 return true;
2415 }
2416
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002419 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002420 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002421
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002423 if (ParseAbsoluteExpression(MaxBytesToFill))
2424 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002425
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002426 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002427 return TokError("unexpected token in directive");
2428 }
2429 }
2430
Sean Callanan79ed1a82010-01-19 20:22:31 +00002431 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002432
Daniel Dunbar648ac512010-05-17 21:54:30 +00002433 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002434 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002435
2436 // Compute alignment in bytes.
2437 if (IsPow2) {
2438 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002439 if (Alignment >= 32) {
2440 Error(AlignmentLoc, "invalid alignment value");
2441 Alignment = 31;
2442 }
2443
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002444 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002445 }
2446
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002447 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 if (MaxBytesLoc.isValid()) {
2449 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002450 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2451 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002452 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002453 }
2454
2455 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002456 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2457 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458 MaxBytesToFill = 0;
2459 }
2460 }
2461
Daniel Dunbar648ac512010-05-17 21:54:30 +00002462 // Check whether we should use optimal code alignment for this .align
2463 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002464 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002465 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2466 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002467 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002468 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002469 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002470 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2471 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002472 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002473
2474 return false;
2475}
2476
Eli Bendersky6ee13082013-01-15 22:59:42 +00002477/// ParseDirectiveFile
2478/// ::= .file [number] filename
2479/// ::= .file number directory filename
2480bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2481 // FIXME: I'm not sure what this is.
2482 int64_t FileNumber = -1;
2483 SMLoc FileNumberLoc = getLexer().getLoc();
2484 if (getLexer().is(AsmToken::Integer)) {
2485 FileNumber = getTok().getIntVal();
2486 Lex();
2487
2488 if (FileNumber < 1)
2489 return TokError("file number less than one");
2490 }
2491
2492 if (getLexer().isNot(AsmToken::String))
2493 return TokError("unexpected token in '.file' directive");
2494
2495 // Usually the directory and filename together, otherwise just the directory.
2496 StringRef Path = getTok().getString();
2497 Path = Path.substr(1, Path.size()-2);
2498 Lex();
2499
2500 StringRef Directory;
2501 StringRef Filename;
2502 if (getLexer().is(AsmToken::String)) {
2503 if (FileNumber == -1)
2504 return TokError("explicit path specified, but no file number");
2505 Filename = getTok().getString();
2506 Filename = Filename.substr(1, Filename.size()-2);
2507 Directory = Path;
2508 Lex();
2509 } else {
2510 Filename = Path;
2511 }
2512
2513 if (getLexer().isNot(AsmToken::EndOfStatement))
2514 return TokError("unexpected token in '.file' directive");
2515
2516 if (FileNumber == -1)
2517 getStreamer().EmitFileDirective(Filename);
2518 else {
2519 if (getContext().getGenDwarfForAssembly() == true)
2520 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2521 "used to generate dwarf debug info for assembly code");
2522
2523 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2524 Error(FileNumberLoc, "file number already allocated");
2525 }
2526
2527 return false;
2528}
2529
2530/// ParseDirectiveLine
2531/// ::= .line [number]
2532bool AsmParser::ParseDirectiveLine() {
2533 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2534 if (getLexer().isNot(AsmToken::Integer))
2535 return TokError("unexpected token in '.line' directive");
2536
2537 int64_t LineNumber = getTok().getIntVal();
2538 (void) LineNumber;
2539 Lex();
2540
2541 // FIXME: Do something with the .line.
2542 }
2543
2544 if (getLexer().isNot(AsmToken::EndOfStatement))
2545 return TokError("unexpected token in '.line' directive");
2546
2547 return false;
2548}
2549
2550/// ParseDirectiveLoc
2551/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2552/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2553/// The first number is a file number, must have been previously assigned with
2554/// a .file directive, the second number is the line number and optionally the
2555/// third number is a column position (zero if not specified). The remaining
2556/// optional items are .loc sub-directives.
2557bool AsmParser::ParseDirectiveLoc() {
2558 if (getLexer().isNot(AsmToken::Integer))
2559 return TokError("unexpected token in '.loc' directive");
2560 int64_t FileNumber = getTok().getIntVal();
2561 if (FileNumber < 1)
2562 return TokError("file number less than one in '.loc' directive");
2563 if (!getContext().isValidDwarfFileNumber(FileNumber))
2564 return TokError("unassigned file number in '.loc' directive");
2565 Lex();
2566
2567 int64_t LineNumber = 0;
2568 if (getLexer().is(AsmToken::Integer)) {
2569 LineNumber = getTok().getIntVal();
2570 if (LineNumber < 1)
2571 return TokError("line number less than one in '.loc' directive");
2572 Lex();
2573 }
2574
2575 int64_t ColumnPos = 0;
2576 if (getLexer().is(AsmToken::Integer)) {
2577 ColumnPos = getTok().getIntVal();
2578 if (ColumnPos < 0)
2579 return TokError("column position less than zero in '.loc' directive");
2580 Lex();
2581 }
2582
2583 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2584 unsigned Isa = 0;
2585 int64_t Discriminator = 0;
2586 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2587 for (;;) {
2588 if (getLexer().is(AsmToken::EndOfStatement))
2589 break;
2590
2591 StringRef Name;
2592 SMLoc Loc = getTok().getLoc();
2593 if (ParseIdentifier(Name))
2594 return TokError("unexpected token in '.loc' directive");
2595
2596 if (Name == "basic_block")
2597 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2598 else if (Name == "prologue_end")
2599 Flags |= DWARF2_FLAG_PROLOGUE_END;
2600 else if (Name == "epilogue_begin")
2601 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2602 else if (Name == "is_stmt") {
2603 Loc = getTok().getLoc();
2604 const MCExpr *Value;
2605 if (ParseExpression(Value))
2606 return true;
2607 // The expression must be the constant 0 or 1.
2608 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2609 int Value = MCE->getValue();
2610 if (Value == 0)
2611 Flags &= ~DWARF2_FLAG_IS_STMT;
2612 else if (Value == 1)
2613 Flags |= DWARF2_FLAG_IS_STMT;
2614 else
2615 return Error(Loc, "is_stmt value not 0 or 1");
2616 }
2617 else {
2618 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2619 }
2620 }
2621 else if (Name == "isa") {
2622 Loc = getTok().getLoc();
2623 const MCExpr *Value;
2624 if (ParseExpression(Value))
2625 return true;
2626 // The expression must be a constant greater or equal to 0.
2627 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2628 int Value = MCE->getValue();
2629 if (Value < 0)
2630 return Error(Loc, "isa number less than zero");
2631 Isa = Value;
2632 }
2633 else {
2634 return Error(Loc, "isa number not a constant value");
2635 }
2636 }
2637 else if (Name == "discriminator") {
2638 if (ParseAbsoluteExpression(Discriminator))
2639 return true;
2640 }
2641 else {
2642 return Error(Loc, "unknown sub-directive in '.loc' directive");
2643 }
2644
2645 if (getLexer().is(AsmToken::EndOfStatement))
2646 break;
2647 }
2648 }
2649
2650 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2651 Isa, Discriminator, StringRef());
2652
2653 return false;
2654}
2655
2656/// ParseDirectiveStabs
2657/// ::= .stabs string, number, number, number
2658bool AsmParser::ParseDirectiveStabs() {
2659 return TokError("unsupported directive '.stabs'");
2660}
2661
2662/// ParseDirectiveCFISections
2663/// ::= .cfi_sections section [, section]
2664bool AsmParser::ParseDirectiveCFISections() {
2665 StringRef Name;
2666 bool EH = false;
2667 bool Debug = false;
2668
2669 if (ParseIdentifier(Name))
2670 return TokError("Expected an identifier");
2671
2672 if (Name == ".eh_frame")
2673 EH = true;
2674 else if (Name == ".debug_frame")
2675 Debug = true;
2676
2677 if (getLexer().is(AsmToken::Comma)) {
2678 Lex();
2679
2680 if (ParseIdentifier(Name))
2681 return TokError("Expected an identifier");
2682
2683 if (Name == ".eh_frame")
2684 EH = true;
2685 else if (Name == ".debug_frame")
2686 Debug = true;
2687 }
2688
2689 getStreamer().EmitCFISections(EH, Debug);
2690 return false;
2691}
2692
2693/// ParseDirectiveCFIStartProc
2694/// ::= .cfi_startproc
2695bool AsmParser::ParseDirectiveCFIStartProc() {
2696 getStreamer().EmitCFIStartProc();
2697 return false;
2698}
2699
2700/// ParseDirectiveCFIEndProc
2701/// ::= .cfi_endproc
2702bool AsmParser::ParseDirectiveCFIEndProc() {
2703 getStreamer().EmitCFIEndProc();
2704 return false;
2705}
2706
2707/// ParseRegisterOrRegisterNumber - parse register name or number.
2708bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2709 SMLoc DirectiveLoc) {
2710 unsigned RegNo;
2711
2712 if (getLexer().isNot(AsmToken::Integer)) {
2713 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2714 return true;
2715 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2716 } else
2717 return ParseAbsoluteExpression(Register);
2718
2719 return false;
2720}
2721
2722/// ParseDirectiveCFIDefCfa
2723/// ::= .cfi_def_cfa register, offset
2724bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2725 int64_t Register = 0;
2726 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2727 return true;
2728
2729 if (getLexer().isNot(AsmToken::Comma))
2730 return TokError("unexpected token in directive");
2731 Lex();
2732
2733 int64_t Offset = 0;
2734 if (ParseAbsoluteExpression(Offset))
2735 return true;
2736
2737 getStreamer().EmitCFIDefCfa(Register, Offset);
2738 return false;
2739}
2740
2741/// ParseDirectiveCFIDefCfaOffset
2742/// ::= .cfi_def_cfa_offset offset
2743bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2744 int64_t Offset = 0;
2745 if (ParseAbsoluteExpression(Offset))
2746 return true;
2747
2748 getStreamer().EmitCFIDefCfaOffset(Offset);
2749 return false;
2750}
2751
2752/// ParseDirectiveCFIRegister
2753/// ::= .cfi_register register, register
2754bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2755 int64_t Register1 = 0;
2756 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2757 return true;
2758
2759 if (getLexer().isNot(AsmToken::Comma))
2760 return TokError("unexpected token in directive");
2761 Lex();
2762
2763 int64_t Register2 = 0;
2764 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2765 return true;
2766
2767 getStreamer().EmitCFIRegister(Register1, Register2);
2768 return false;
2769}
2770
2771/// ParseDirectiveCFIAdjustCfaOffset
2772/// ::= .cfi_adjust_cfa_offset adjustment
2773bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2774 int64_t Adjustment = 0;
2775 if (ParseAbsoluteExpression(Adjustment))
2776 return true;
2777
2778 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2779 return false;
2780}
2781
2782/// ParseDirectiveCFIDefCfaRegister
2783/// ::= .cfi_def_cfa_register register
2784bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2785 int64_t Register = 0;
2786 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2787 return true;
2788
2789 getStreamer().EmitCFIDefCfaRegister(Register);
2790 return false;
2791}
2792
2793/// ParseDirectiveCFIOffset
2794/// ::= .cfi_offset register, offset
2795bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2796 int64_t Register = 0;
2797 int64_t Offset = 0;
2798
2799 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2800 return true;
2801
2802 if (getLexer().isNot(AsmToken::Comma))
2803 return TokError("unexpected token in directive");
2804 Lex();
2805
2806 if (ParseAbsoluteExpression(Offset))
2807 return true;
2808
2809 getStreamer().EmitCFIOffset(Register, Offset);
2810 return false;
2811}
2812
2813/// ParseDirectiveCFIRelOffset
2814/// ::= .cfi_rel_offset register, offset
2815bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2816 int64_t Register = 0;
2817
2818 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2819 return true;
2820
2821 if (getLexer().isNot(AsmToken::Comma))
2822 return TokError("unexpected token in directive");
2823 Lex();
2824
2825 int64_t Offset = 0;
2826 if (ParseAbsoluteExpression(Offset))
2827 return true;
2828
2829 getStreamer().EmitCFIRelOffset(Register, Offset);
2830 return false;
2831}
2832
2833static bool isValidEncoding(int64_t Encoding) {
2834 if (Encoding & ~0xff)
2835 return false;
2836
2837 if (Encoding == dwarf::DW_EH_PE_omit)
2838 return true;
2839
2840 const unsigned Format = Encoding & 0xf;
2841 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2842 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2843 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2844 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2845 return false;
2846
2847 const unsigned Application = Encoding & 0x70;
2848 if (Application != dwarf::DW_EH_PE_absptr &&
2849 Application != dwarf::DW_EH_PE_pcrel)
2850 return false;
2851
2852 return true;
2853}
2854
2855/// ParseDirectiveCFIPersonalityOrLsda
2856/// IsPersonality true for cfi_personality, false for cfi_lsda
2857/// ::= .cfi_personality encoding, [symbol_name]
2858/// ::= .cfi_lsda encoding, [symbol_name]
2859bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2860 int64_t Encoding = 0;
2861 if (ParseAbsoluteExpression(Encoding))
2862 return true;
2863 if (Encoding == dwarf::DW_EH_PE_omit)
2864 return false;
2865
2866 if (!isValidEncoding(Encoding))
2867 return TokError("unsupported encoding.");
2868
2869 if (getLexer().isNot(AsmToken::Comma))
2870 return TokError("unexpected token in directive");
2871 Lex();
2872
2873 StringRef Name;
2874 if (ParseIdentifier(Name))
2875 return TokError("expected identifier in directive");
2876
2877 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2878
2879 if (IsPersonality)
2880 getStreamer().EmitCFIPersonality(Sym, Encoding);
2881 else
2882 getStreamer().EmitCFILsda(Sym, Encoding);
2883 return false;
2884}
2885
2886/// ParseDirectiveCFIRememberState
2887/// ::= .cfi_remember_state
2888bool AsmParser::ParseDirectiveCFIRememberState() {
2889 getStreamer().EmitCFIRememberState();
2890 return false;
2891}
2892
2893/// ParseDirectiveCFIRestoreState
2894/// ::= .cfi_remember_state
2895bool AsmParser::ParseDirectiveCFIRestoreState() {
2896 getStreamer().EmitCFIRestoreState();
2897 return false;
2898}
2899
2900/// ParseDirectiveCFISameValue
2901/// ::= .cfi_same_value register
2902bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2903 int64_t Register = 0;
2904
2905 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2906 return true;
2907
2908 getStreamer().EmitCFISameValue(Register);
2909 return false;
2910}
2911
2912/// ParseDirectiveCFIRestore
2913/// ::= .cfi_restore register
2914bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2915 int64_t Register = 0;
2916 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2917 return true;
2918
2919 getStreamer().EmitCFIRestore(Register);
2920 return false;
2921}
2922
2923/// ParseDirectiveCFIEscape
2924/// ::= .cfi_escape expression[,...]
2925bool AsmParser::ParseDirectiveCFIEscape() {
2926 std::string Values;
2927 int64_t CurrValue;
2928 if (ParseAbsoluteExpression(CurrValue))
2929 return true;
2930
2931 Values.push_back((uint8_t)CurrValue);
2932
2933 while (getLexer().is(AsmToken::Comma)) {
2934 Lex();
2935
2936 if (ParseAbsoluteExpression(CurrValue))
2937 return true;
2938
2939 Values.push_back((uint8_t)CurrValue);
2940 }
2941
2942 getStreamer().EmitCFIEscape(Values);
2943 return false;
2944}
2945
2946/// ParseDirectiveCFISignalFrame
2947/// ::= .cfi_signal_frame
2948bool AsmParser::ParseDirectiveCFISignalFrame() {
2949 if (getLexer().isNot(AsmToken::EndOfStatement))
2950 return Error(getLexer().getLoc(),
2951 "unexpected token in '.cfi_signal_frame'");
2952
2953 getStreamer().EmitCFISignalFrame();
2954 return false;
2955}
2956
2957/// ParseDirectiveCFIUndefined
2958/// ::= .cfi_undefined register
2959bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2960 int64_t Register = 0;
2961
2962 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2963 return true;
2964
2965 getStreamer().EmitCFIUndefined(Register);
2966 return false;
2967}
2968
2969/// ParseDirectiveMacrosOnOff
2970/// ::= .macros_on
2971/// ::= .macros_off
2972bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2973 if (getLexer().isNot(AsmToken::EndOfStatement))
2974 return Error(getLexer().getLoc(),
2975 "unexpected token in '" + Directive + "' directive");
2976
2977 SetMacrosEnabled(Directive == ".macros_on");
2978 return false;
2979}
2980
2981/// ParseDirectiveMacro
2982/// ::= .macro name [parameters]
2983bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2984 StringRef Name;
2985 if (ParseIdentifier(Name))
2986 return TokError("expected identifier in '.macro' directive");
2987
2988 MCAsmMacroParameters Parameters;
2989 // Argument delimiter is initially unknown. It will be set by
2990 // ParseMacroArgument()
2991 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2992 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2993 for (;;) {
2994 MCAsmMacroParameter Parameter;
2995 if (ParseIdentifier(Parameter.first))
2996 return TokError("expected identifier in '.macro' directive");
2997
2998 if (getLexer().is(AsmToken::Equal)) {
2999 Lex();
3000 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3001 return true;
3002 }
3003
3004 Parameters.push_back(Parameter);
3005
3006 if (getLexer().is(AsmToken::Comma))
3007 Lex();
3008 else if (getLexer().is(AsmToken::EndOfStatement))
3009 break;
3010 }
3011 }
3012
3013 // Eat the end of statement.
3014 Lex();
3015
3016 AsmToken EndToken, StartToken = getTok();
3017
3018 // Lex the macro definition.
3019 for (;;) {
3020 // Check whether we have reached the end of the file.
3021 if (getLexer().is(AsmToken::Eof))
3022 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3023
3024 // Otherwise, check whether we have reach the .endmacro.
3025 if (getLexer().is(AsmToken::Identifier) &&
3026 (getTok().getIdentifier() == ".endm" ||
3027 getTok().getIdentifier() == ".endmacro")) {
3028 EndToken = getTok();
3029 Lex();
3030 if (getLexer().isNot(AsmToken::EndOfStatement))
3031 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3032 "' directive");
3033 break;
3034 }
3035
3036 // Otherwise, scan til the end of the statement.
3037 EatToEndOfStatement();
3038 }
3039
3040 if (LookupMacro(Name)) {
3041 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3042 }
3043
3044 const char *BodyStart = StartToken.getLoc().getPointer();
3045 const char *BodyEnd = EndToken.getLoc().getPointer();
3046 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3047 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3048 return false;
3049}
3050
3051/// ParseDirectiveEndMacro
3052/// ::= .endm
3053/// ::= .endmacro
3054bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3055 if (getLexer().isNot(AsmToken::EndOfStatement))
3056 return TokError("unexpected token in '" + Directive + "' directive");
3057
3058 // If we are inside a macro instantiation, terminate the current
3059 // instantiation.
3060 if (InsideMacroInstantiation()) {
3061 HandleMacroExit();
3062 return false;
3063 }
3064
3065 // Otherwise, this .endmacro is a stray entry in the file; well formed
3066 // .endmacro directives are handled during the macro definition parsing.
3067 return TokError("unexpected '" + Directive + "' in file, "
3068 "no current macro definition");
3069}
3070
3071/// ParseDirectivePurgeMacro
3072/// ::= .purgem
3073bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3074 StringRef Name;
3075 if (ParseIdentifier(Name))
3076 return TokError("expected identifier in '.purgem' directive");
3077
3078 if (getLexer().isNot(AsmToken::EndOfStatement))
3079 return TokError("unexpected token in '.purgem' directive");
3080
3081 if (!LookupMacro(Name))
3082 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3083
3084 UndefineMacro(Name);
3085 return false;
3086}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003087
3088/// ParseDirectiveBundleAlignMode
3089/// ::= {.bundle_align_mode} expression
3090bool AsmParser::ParseDirectiveBundleAlignMode() {
3091 CheckForValidSection();
3092
3093 // Expect a single argument: an expression that evaluates to a constant
3094 // in the inclusive range 0-30.
3095 SMLoc ExprLoc = getLexer().getLoc();
3096 int64_t AlignSizePow2;
3097 if (ParseAbsoluteExpression(AlignSizePow2))
3098 return true;
3099 else if (getLexer().isNot(AsmToken::EndOfStatement))
3100 return TokError("unexpected token after expression in"
3101 " '.bundle_align_mode' directive");
3102 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3103 return Error(ExprLoc,
3104 "invalid bundle alignment size (expected between 0 and 30)");
3105
3106 Lex();
3107
3108 // Because of AlignSizePow2's verified range we can safely truncate it to
3109 // unsigned.
3110 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3111 return false;
3112}
3113
3114/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003115/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003116bool AsmParser::ParseDirectiveBundleLock() {
3117 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003118 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003119
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003120 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3121 StringRef Option;
3122 SMLoc Loc = getTok().getLoc();
3123 const char *kInvalidOptionError =
3124 "invalid option for '.bundle_lock' directive";
3125
3126 if (ParseIdentifier(Option))
3127 return Error(Loc, kInvalidOptionError);
3128
3129 if (Option != "align_to_end")
3130 return Error(Loc, kInvalidOptionError);
3131 else if (getLexer().isNot(AsmToken::EndOfStatement))
3132 return Error(Loc,
3133 "unexpected token after '.bundle_lock' directive option");
3134 AlignToEnd = true;
3135 }
3136
Eli Bendersky4766ef42012-12-20 19:05:53 +00003137 Lex();
3138
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003139 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003140 return false;
3141}
3142
3143/// ParseDirectiveBundleLock
3144/// ::= {.bundle_lock}
3145bool AsmParser::ParseDirectiveBundleUnlock() {
3146 CheckForValidSection();
3147
3148 if (getLexer().isNot(AsmToken::EndOfStatement))
3149 return TokError("unexpected token in '.bundle_unlock' directive");
3150 Lex();
3151
3152 getStreamer().EmitBundleUnlock();
3153 return false;
3154}
3155
Eli Bendersky6ee13082013-01-15 22:59:42 +00003156/// ParseDirectiveSpace
3157/// ::= (.skip | .space) expression [ , expression ]
3158bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3159 CheckForValidSection();
3160
3161 int64_t NumBytes;
3162 if (ParseAbsoluteExpression(NumBytes))
3163 return true;
3164
3165 int64_t FillExpr = 0;
3166 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3167 if (getLexer().isNot(AsmToken::Comma))
3168 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3169 Lex();
3170
3171 if (ParseAbsoluteExpression(FillExpr))
3172 return true;
3173
3174 if (getLexer().isNot(AsmToken::EndOfStatement))
3175 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3176 }
3177
3178 Lex();
3179
3180 if (NumBytes <= 0)
3181 return TokError("invalid number of bytes in '" +
3182 Twine(IDVal) + "' directive");
3183
3184 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3185 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3186
3187 return false;
3188}
3189
3190/// ParseDirectiveLEB128
3191/// ::= (.sleb128 | .uleb128) expression
3192bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3193 CheckForValidSection();
3194 const MCExpr *Value;
3195
3196 if (ParseExpression(Value))
3197 return true;
3198
3199 if (getLexer().isNot(AsmToken::EndOfStatement))
3200 return TokError("unexpected token in directive");
3201
3202 if (Signed)
3203 getStreamer().EmitSLEB128Value(Value);
3204 else
3205 getStreamer().EmitULEB128Value(Value);
3206
3207 return false;
3208}
3209
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003210/// ParseDirectiveSymbolAttribute
3211/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003212bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003213 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003214 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003215 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003216 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003217
3218 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003219 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003220
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003221 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003222
Jim Grosbach10ec6502011-09-15 17:56:49 +00003223 // Assembler local symbols don't make any sense here. Complain loudly.
3224 if (Sym->isTemporary())
3225 return Error(Loc, "non-local symbol required in directive");
3226
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003227 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003228
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003229 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003230 break;
3231
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003232 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003233 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003234 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003235 }
3236 }
3237
Sean Callanan79ed1a82010-01-19 20:22:31 +00003238 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003239 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003240}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003241
3242/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003243/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3244bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003245 CheckForValidSection();
3246
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003247 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003248 StringRef Name;
3249 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003250 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003251
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003252 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003253 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003254
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003255 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003256 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003257 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003258
3259 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003260 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003261 if (ParseAbsoluteExpression(Size))
3262 return true;
3263
3264 int64_t Pow2Alignment = 0;
3265 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003266 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003267 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003268 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003269 if (ParseAbsoluteExpression(Pow2Alignment))
3270 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003271
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003272 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3273 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003274 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3275
Chris Lattner258281d2010-01-19 06:22:22 +00003276 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003277 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3278 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003279 if (!isPowerOf2_64(Pow2Alignment))
3280 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3281 Pow2Alignment = Log2_64(Pow2Alignment);
3282 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003283 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003284
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003285 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003286 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003287
Sean Callanan79ed1a82010-01-19 20:22:31 +00003288 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003289
Chris Lattner1fc3d752009-07-09 17:25:12 +00003290 // NOTE: a size of zero for a .comm should create a undefined symbol
3291 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003292 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003293 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3294 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003295
Eric Christopherc260a3e2010-05-14 01:38:54 +00003296 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003297 // may internally end up wanting an alignment in bytes.
3298 // FIXME: Diagnose overflow.
3299 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003300 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3301 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003302
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003303 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003304 return Error(IDLoc, "invalid symbol redefinition");
3305
Chris Lattner1fc3d752009-07-09 17:25:12 +00003306 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003307 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003308 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003309 return false;
3310 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003311
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003312 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003313 return false;
3314}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003315
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003316/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003317/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003318bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003319 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003320 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003321
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003322 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003323 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003324 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003325
Sean Callanan79ed1a82010-01-19 20:22:31 +00003326 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003327
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003328 if (Str.empty())
3329 Error(Loc, ".abort detected. Assembly stopping.");
3330 else
3331 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003332 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003333
3334 return false;
3335}
Kevin Enderby71148242009-07-14 21:35:03 +00003336
Kevin Enderby1f049b22009-07-14 23:21:55 +00003337/// ParseDirectiveInclude
3338/// ::= .include "filename"
3339bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003340 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003341 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003342
Sean Callanan18b83232010-01-19 21:44:56 +00003343 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003344 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003345 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003346
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003347 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003348 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003349
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003350 // Strip the quotes.
3351 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003352
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003353 // Attempt to switch the lexer to the included file before consuming the end
3354 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003355 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003356 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003357 return true;
3358 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003359
3360 return false;
3361}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003362
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003363/// ParseDirectiveIncbin
3364/// ::= .incbin "filename"
3365bool AsmParser::ParseDirectiveIncbin() {
3366 if (getLexer().isNot(AsmToken::String))
3367 return TokError("expected string in '.incbin' directive");
3368
3369 std::string Filename = getTok().getString();
3370 SMLoc IncbinLoc = getLexer().getLoc();
3371 Lex();
3372
3373 if (getLexer().isNot(AsmToken::EndOfStatement))
3374 return TokError("unexpected token in '.incbin' directive");
3375
3376 // Strip the quotes.
3377 Filename = Filename.substr(1, Filename.size()-2);
3378
3379 // Attempt to process the included file.
3380 if (ProcessIncbinFile(Filename)) {
3381 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3382 return true;
3383 }
3384
3385 return false;
3386}
3387
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003388/// ParseDirectiveIf
3389/// ::= .if expression
3390bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003391 TheCondStack.push_back(TheCondState);
3392 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003393 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003394 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003395 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003396 int64_t ExprValue;
3397 if (ParseAbsoluteExpression(ExprValue))
3398 return true;
3399
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003400 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003401 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003402
Sean Callanan79ed1a82010-01-19 20:22:31 +00003403 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003404
3405 TheCondState.CondMet = ExprValue;
3406 TheCondState.Ignore = !TheCondState.CondMet;
3407 }
3408
3409 return false;
3410}
3411
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003412/// ParseDirectiveIfb
3413/// ::= .ifb string
3414bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3415 TheCondStack.push_back(TheCondState);
3416 TheCondState.TheCond = AsmCond::IfCond;
3417
Benjamin Kramer29739e72012-05-12 16:52:21 +00003418 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003419 EatToEndOfStatement();
3420 } else {
3421 StringRef Str = ParseStringToEndOfStatement();
3422
3423 if (getLexer().isNot(AsmToken::EndOfStatement))
3424 return TokError("unexpected token in '.ifb' directive");
3425
3426 Lex();
3427
3428 TheCondState.CondMet = ExpectBlank == Str.empty();
3429 TheCondState.Ignore = !TheCondState.CondMet;
3430 }
3431
3432 return false;
3433}
3434
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003435/// ParseDirectiveIfc
3436/// ::= .ifc string1, string2
3437bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3438 TheCondStack.push_back(TheCondState);
3439 TheCondState.TheCond = AsmCond::IfCond;
3440
Benjamin Kramer29739e72012-05-12 16:52:21 +00003441 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003442 EatToEndOfStatement();
3443 } else {
3444 StringRef Str1 = ParseStringToComma();
3445
3446 if (getLexer().isNot(AsmToken::Comma))
3447 return TokError("unexpected token in '.ifc' directive");
3448
3449 Lex();
3450
3451 StringRef Str2 = ParseStringToEndOfStatement();
3452
3453 if (getLexer().isNot(AsmToken::EndOfStatement))
3454 return TokError("unexpected token in '.ifc' directive");
3455
3456 Lex();
3457
3458 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3459 TheCondState.Ignore = !TheCondState.CondMet;
3460 }
3461
3462 return false;
3463}
3464
3465/// ParseDirectiveIfdef
3466/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003467bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3468 StringRef Name;
3469 TheCondStack.push_back(TheCondState);
3470 TheCondState.TheCond = AsmCond::IfCond;
3471
3472 if (TheCondState.Ignore) {
3473 EatToEndOfStatement();
3474 } else {
3475 if (ParseIdentifier(Name))
3476 return TokError("expected identifier after '.ifdef'");
3477
3478 Lex();
3479
3480 MCSymbol *Sym = getContext().LookupSymbol(Name);
3481
3482 if (expect_defined)
3483 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3484 else
3485 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3486 TheCondState.Ignore = !TheCondState.CondMet;
3487 }
3488
3489 return false;
3490}
3491
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003492/// ParseDirectiveElseIf
3493/// ::= .elseif expression
3494bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3495 if (TheCondState.TheCond != AsmCond::IfCond &&
3496 TheCondState.TheCond != AsmCond::ElseIfCond)
3497 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3498 " an .elseif");
3499 TheCondState.TheCond = AsmCond::ElseIfCond;
3500
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003501 bool LastIgnoreState = false;
3502 if (!TheCondStack.empty())
3503 LastIgnoreState = TheCondStack.back().Ignore;
3504 if (LastIgnoreState || TheCondState.CondMet) {
3505 TheCondState.Ignore = true;
3506 EatToEndOfStatement();
3507 }
3508 else {
3509 int64_t ExprValue;
3510 if (ParseAbsoluteExpression(ExprValue))
3511 return true;
3512
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003513 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003514 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003515
Sean Callanan79ed1a82010-01-19 20:22:31 +00003516 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003517 TheCondState.CondMet = ExprValue;
3518 TheCondState.Ignore = !TheCondState.CondMet;
3519 }
3520
3521 return false;
3522}
3523
3524/// ParseDirectiveElse
3525/// ::= .else
3526bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003527 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003528 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003529
Sean Callanan79ed1a82010-01-19 20:22:31 +00003530 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003531
3532 if (TheCondState.TheCond != AsmCond::IfCond &&
3533 TheCondState.TheCond != AsmCond::ElseIfCond)
3534 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3535 ".elseif");
3536 TheCondState.TheCond = AsmCond::ElseCond;
3537 bool LastIgnoreState = false;
3538 if (!TheCondStack.empty())
3539 LastIgnoreState = TheCondStack.back().Ignore;
3540 if (LastIgnoreState || TheCondState.CondMet)
3541 TheCondState.Ignore = true;
3542 else
3543 TheCondState.Ignore = false;
3544
3545 return false;
3546}
3547
3548/// ParseDirectiveEndIf
3549/// ::= .endif
3550bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003551 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003552 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003553
Sean Callanan79ed1a82010-01-19 20:22:31 +00003554 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003555
3556 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3557 TheCondStack.empty())
3558 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3559 ".else");
3560 if (!TheCondStack.empty()) {
3561 TheCondState = TheCondStack.back();
3562 TheCondStack.pop_back();
3563 }
3564
3565 return false;
3566}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003567
Eli Bendersky6ee13082013-01-15 22:59:42 +00003568void AsmParser::initializeDirectiveKindMap() {
3569 DirectiveKindMap[".set"] = DK_SET;
3570 DirectiveKindMap[".equ"] = DK_EQU;
3571 DirectiveKindMap[".equiv"] = DK_EQUIV;
3572 DirectiveKindMap[".ascii"] = DK_ASCII;
3573 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3574 DirectiveKindMap[".string"] = DK_STRING;
3575 DirectiveKindMap[".byte"] = DK_BYTE;
3576 DirectiveKindMap[".short"] = DK_SHORT;
3577 DirectiveKindMap[".value"] = DK_VALUE;
3578 DirectiveKindMap[".2byte"] = DK_2BYTE;
3579 DirectiveKindMap[".long"] = DK_LONG;
3580 DirectiveKindMap[".int"] = DK_INT;
3581 DirectiveKindMap[".4byte"] = DK_4BYTE;
3582 DirectiveKindMap[".quad"] = DK_QUAD;
3583 DirectiveKindMap[".8byte"] = DK_8BYTE;
3584 DirectiveKindMap[".single"] = DK_SINGLE;
3585 DirectiveKindMap[".float"] = DK_FLOAT;
3586 DirectiveKindMap[".double"] = DK_DOUBLE;
3587 DirectiveKindMap[".align"] = DK_ALIGN;
3588 DirectiveKindMap[".align32"] = DK_ALIGN32;
3589 DirectiveKindMap[".balign"] = DK_BALIGN;
3590 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3591 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3592 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3593 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3594 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3595 DirectiveKindMap[".org"] = DK_ORG;
3596 DirectiveKindMap[".fill"] = DK_FILL;
3597 DirectiveKindMap[".zero"] = DK_ZERO;
3598 DirectiveKindMap[".extern"] = DK_EXTERN;
3599 DirectiveKindMap[".globl"] = DK_GLOBL;
3600 DirectiveKindMap[".global"] = DK_GLOBAL;
3601 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3602 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3603 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3604 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3605 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3606 DirectiveKindMap[".reference"] = DK_REFERENCE;
3607 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3608 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3609 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3610 DirectiveKindMap[".comm"] = DK_COMM;
3611 DirectiveKindMap[".common"] = DK_COMMON;
3612 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3613 DirectiveKindMap[".abort"] = DK_ABORT;
3614 DirectiveKindMap[".include"] = DK_INCLUDE;
3615 DirectiveKindMap[".incbin"] = DK_INCBIN;
3616 DirectiveKindMap[".code16"] = DK_CODE16;
3617 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3618 DirectiveKindMap[".rept"] = DK_REPT;
3619 DirectiveKindMap[".irp"] = DK_IRP;
3620 DirectiveKindMap[".irpc"] = DK_IRPC;
3621 DirectiveKindMap[".endr"] = DK_ENDR;
3622 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3623 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3624 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3625 DirectiveKindMap[".if"] = DK_IF;
3626 DirectiveKindMap[".ifb"] = DK_IFB;
3627 DirectiveKindMap[".ifnb"] = DK_IFNB;
3628 DirectiveKindMap[".ifc"] = DK_IFC;
3629 DirectiveKindMap[".ifnc"] = DK_IFNC;
3630 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3631 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3632 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3633 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3634 DirectiveKindMap[".else"] = DK_ELSE;
3635 DirectiveKindMap[".endif"] = DK_ENDIF;
3636 DirectiveKindMap[".skip"] = DK_SKIP;
3637 DirectiveKindMap[".space"] = DK_SPACE;
3638 DirectiveKindMap[".file"] = DK_FILE;
3639 DirectiveKindMap[".line"] = DK_LINE;
3640 DirectiveKindMap[".loc"] = DK_LOC;
3641 DirectiveKindMap[".stabs"] = DK_STABS;
3642 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3643 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3644 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3645 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3646 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3647 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3648 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3649 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3650 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3651 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3652 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3653 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3654 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3655 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3656 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3657 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3658 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3659 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3660 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3661 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3662 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3663 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3664 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3665 DirectiveKindMap[".macro"] = DK_MACRO;
3666 DirectiveKindMap[".endm"] = DK_ENDM;
3667 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3668 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003669}
3670
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003671
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003672MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003673 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003674
Rafael Espindola761cb062012-06-03 23:57:14 +00003675 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003676 for (;;) {
3677 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003678 if (getLexer().is(AsmToken::Eof)) {
3679 Error(DirectiveLoc, "no matching '.endr' in definition");
3680 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003681 }
3682
Rafael Espindola761cb062012-06-03 23:57:14 +00003683 if (Lexer.is(AsmToken::Identifier) &&
3684 (getTok().getIdentifier() == ".rept")) {
3685 ++NestLevel;
3686 }
3687
3688 // Otherwise, check whether we have reached the .endr.
3689 if (Lexer.is(AsmToken::Identifier) &&
3690 getTok().getIdentifier() == ".endr") {
3691 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003692 EndToken = getTok();
3693 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003694 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3695 TokError("unexpected token in '.endr' directive");
3696 return 0;
3697 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003698 break;
3699 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003700 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003701 }
3702
Rafael Espindola761cb062012-06-03 23:57:14 +00003703 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003704 EatToEndOfStatement();
3705 }
3706
3707 const char *BodyStart = StartToken.getLoc().getPointer();
3708 const char *BodyEnd = EndToken.getLoc().getPointer();
3709 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3710
Rafael Espindola761cb062012-06-03 23:57:14 +00003711 // We Are Anonymous.
3712 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003713 MCAsmMacroParameters Parameters;
3714 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003715}
3716
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003717void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003718 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003719 OS << ".endr\n";
3720
3721 MemoryBuffer *Instantiation =
3722 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3723
Rafael Espindola761cb062012-06-03 23:57:14 +00003724 // Create the macro instantiation object and add to the current macro
3725 // instantiation stack.
3726 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003727 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003728 getTok().getLoc(),
3729 Instantiation);
3730 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003731
Rafael Espindola761cb062012-06-03 23:57:14 +00003732 // Jump to the macro instantiation and prime the lexer.
3733 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3734 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3735 Lex();
3736}
3737
3738bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3739 int64_t Count;
3740 if (ParseAbsoluteExpression(Count))
3741 return TokError("unexpected token in '.rept' directive");
3742
3743 if (Count < 0)
3744 return TokError("Count is negative");
3745
3746 if (Lexer.isNot(AsmToken::EndOfStatement))
3747 return TokError("unexpected token in '.rept' directive");
3748
3749 // Eat the end of statement.
3750 Lex();
3751
3752 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003753 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003754 if (!M)
3755 return true;
3756
3757 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3758 // to hold the macro body with substitutions.
3759 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003760 MCAsmMacroParameters Parameters;
3761 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003762 raw_svector_ostream OS(Buf);
3763 while (Count--) {
3764 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3765 return true;
3766 }
3767 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003768
3769 return false;
3770}
3771
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003772/// ParseDirectiveIrp
3773/// ::= .irp symbol,values
3774bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003775 MCAsmMacroParameters Parameters;
3776 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003777
Preston Gurd6c9176a2012-09-19 20:29:04 +00003778 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003779 return TokError("expected identifier in '.irp' directive");
3780
3781 Parameters.push_back(Parameter);
3782
3783 if (Lexer.isNot(AsmToken::Comma))
3784 return TokError("expected comma in '.irp' directive");
3785
3786 Lex();
3787
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003788 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003789 if (ParseMacroArguments(0, A))
3790 return true;
3791
3792 // Eat the end of statement.
3793 Lex();
3794
3795 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003796 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003797 if (!M)
3798 return true;
3799
3800 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3801 // to hold the macro body with substitutions.
3802 SmallString<256> Buf;
3803 raw_svector_ostream OS(Buf);
3804
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003805 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3806 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003807 Args.push_back(*i);
3808
3809 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3810 return true;
3811 }
3812
3813 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3814
3815 return false;
3816}
3817
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003818/// ParseDirectiveIrpc
3819/// ::= .irpc symbol,values
3820bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003821 MCAsmMacroParameters Parameters;
3822 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003823
Preston Gurd6c9176a2012-09-19 20:29:04 +00003824 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003825 return TokError("expected identifier in '.irpc' directive");
3826
3827 Parameters.push_back(Parameter);
3828
3829 if (Lexer.isNot(AsmToken::Comma))
3830 return TokError("expected comma in '.irpc' directive");
3831
3832 Lex();
3833
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003834 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003835 if (ParseMacroArguments(0, A))
3836 return true;
3837
3838 if (A.size() != 1 || A.front().size() != 1)
3839 return TokError("unexpected token in '.irpc' directive");
3840
3841 // Eat the end of statement.
3842 Lex();
3843
3844 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003845 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003846 if (!M)
3847 return true;
3848
3849 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3850 // to hold the macro body with substitutions.
3851 SmallString<256> Buf;
3852 raw_svector_ostream OS(Buf);
3853
3854 StringRef Values = A.front().front().getString();
3855 std::size_t I, End = Values.size();
3856 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003857 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003858 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3859
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003860 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003861 Args.push_back(Arg);
3862
3863 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3864 return true;
3865 }
3866
3867 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3868
3869 return false;
3870}
3871
Rafael Espindola761cb062012-06-03 23:57:14 +00003872bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3873 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003874 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003875
3876 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003877 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003878 assert(getLexer().is(AsmToken::EndOfStatement));
3879
Rafael Espindola761cb062012-06-03 23:57:14 +00003880 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003881 return false;
3882}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003883
Eli Friedman2128aae2012-10-22 23:58:19 +00003884bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3885 const MCExpr *Value;
3886 SMLoc ExprLoc = getLexer().getLoc();
3887 if (ParseExpression(Value))
3888 return true;
3889 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3890 if (!MCE)
3891 return Error(ExprLoc, "unexpected expression in _emit");
3892 uint64_t IntValue = MCE->getValue();
3893 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3894 return Error(ExprLoc, "literal value out of range for directive");
3895
3896 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3897 return false;
3898}
3899
Chad Rosierb1f8c132012-10-18 15:49:34 +00003900bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3901 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003902 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003903 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003904 SmallVectorImpl<std::string> &Clobbers,
3905 const MCInstrInfo *MII,
3906 const MCInstPrinter *IP,
3907 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003908 SmallVector<void *, 4> InputDecls;
3909 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003910 SmallVector<bool, 4> InputDeclsAddressOf;
3911 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003912 SmallVector<std::string, 4> InputConstraints;
3913 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003914 std::set<std::string> ClobberRegs;
3915
Chad Rosier4e472d22012-10-20 01:02:45 +00003916 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003917
3918 // Prime the lexer.
3919 Lex();
3920
3921 // While we have input, parse each statement.
3922 unsigned InputIdx = 0;
3923 unsigned OutputIdx = 0;
3924 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003925 ParseStatementInfo Info(&AsmStrRewrites);
3926 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003927 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003928
Chad Rosier57498012012-12-12 22:45:52 +00003929 if (Info.ParseError)
3930 return true;
3931
Eli Friedman2128aae2012-10-22 23:58:19 +00003932 if (Info.Opcode != ~0U) {
3933 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003934
3935 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003936 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3937 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003938
3939 // Immediate.
3940 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003941 if (Operand->needAsmRewrite())
3942 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3943 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003944 continue;
3945 }
3946
3947 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003948 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003949 unsigned NumDefs = Desc.getNumDefs();
3950 // Clobber.
3951 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3952 std::string Reg;
3953 raw_string_ostream OS(Reg);
3954 IP->printRegName(OS, Operand->getReg());
3955 ClobberRegs.insert(StringRef(OS.str()));
3956 }
3957 continue;
3958 }
3959
3960 // Expr/Input or Output.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003961 bool IsVarDecl;
Chad Rosier505bca32013-01-17 19:21:48 +00003962 unsigned Length, Size, Type;
Chad Rosier32989592012-10-18 20:27:15 +00003963 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosier505bca32013-01-17 19:21:48 +00003964 Length, Size, Type, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003965 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003966 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00003967 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003968 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003969 Operand->getStartLoc(),
3970 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003971 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003972 if (isOutput) {
3973 std::string Constraint = "=";
3974 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003975 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003976 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003977 Constraint += Operand->getConstraint().str();
3978 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003979 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003980 Operand->getStartLoc(),
3981 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003982 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003983 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003984 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003985 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003986 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003987 Operand->getStartLoc(),
3988 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003989 }
3990 }
3991 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003992 }
3993 }
3994
3995 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003996 NumOutputs = OutputDecls.size();
3997 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003998
3999 // Set the unique clobbers.
4000 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4001 E = ClobberRegs.end(); I != E; ++I)
4002 Clobbers.push_back(*I);
4003
4004 // Merge the various outputs and inputs. Output are expected first.
4005 if (NumOutputs || NumInputs) {
4006 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004007 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004008 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004009 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004010 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004011 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004012 }
4013 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004014 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004015 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004016 }
4017 }
4018
4019 // Build the IR assembly string.
4020 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004021 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004022 raw_string_ostream OS(AsmStringIR);
4023 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00004024 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004025 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4026 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004027
Chad Rosier4e472d22012-10-20 01:02:45 +00004028 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004029
4030 // Emit everything up to the immediate/expression. If the previous rewrite
4031 // was a size directive, then this has already been done.
4032 if (PrevKind != AOK_SizeDirective)
4033 OS << StringRef(Start, Loc - Start);
4034 PrevKind = Kind;
4035
Chad Rosier5a719fc2012-10-23 17:43:43 +00004036 // Skip the original expression.
4037 if (Kind == AOK_Skip) {
4038 Start = Loc + (*I).Len;
4039 continue;
4040 }
4041
Chad Rosierb1f8c132012-10-18 15:49:34 +00004042 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004043 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004044 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004045 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004046 OS << Twine("$$");
4047 OS << (*I).Val;
4048 break;
4049 case AOK_ImmPrefix:
4050 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004051 break;
4052 case AOK_Input:
4053 OS << '$';
4054 OS << InputIdx++;
4055 break;
4056 case AOK_Output:
4057 OS << '$';
4058 OS << OutputIdx++;
4059 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004060 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004061 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004062 default: break;
4063 case 8: OS << "byte ptr "; break;
4064 case 16: OS << "word ptr "; break;
4065 case 32: OS << "dword ptr "; break;
4066 case 64: OS << "qword ptr "; break;
4067 case 80: OS << "xword ptr "; break;
4068 case 128: OS << "xmmword ptr "; break;
4069 case 256: OS << "ymmword ptr "; break;
4070 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004071 break;
4072 case AOK_Emit:
4073 OS << ".byte";
4074 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004075 case AOK_DotOperator:
4076 OS << (*I).Val;
4077 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004078 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004079
Chad Rosierb1f8c132012-10-18 15:49:34 +00004080 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004081 if (Kind != AOK_SizeDirective)
4082 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004083 }
4084
4085 // Emit the remainder of the asm string.
4086 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4087 if (Start != AsmEnd)
4088 OS << StringRef(Start, AsmEnd - Start);
4089
4090 AsmString = OS.str();
4091 return false;
4092}
4093
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004094/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004095MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004096 MCContext &C, MCStreamer &Out,
4097 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004098 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004099}