blob: bd2c65e64644ee924ee8a443c38d9ed898d8acdc [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
Kevin Enderby221514e2013-01-22 21:44:53 +0000240 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
241 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000242 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000243 const MCAsmMacroParameters &Parameters,
244 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000245 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000246
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000247 /// \brief Are macros enabled in the parser?
248 bool MacrosEnabled() {return MacrosEnabledFlag;}
249
250 /// \brief Control a flag in the parser that enables or disables macros.
251 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
252
253 /// \brief Lookup a previously defined macro.
254 /// \param Name Macro name.
255 /// \returns Pointer to macro. NULL if no such macro was defined.
256 const MCAsmMacro* LookupMacro(StringRef Name);
257
258 /// \brief Define a new macro with the given name and information.
259 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
260
261 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
262 void UndefineMacro(StringRef Name);
263
264 /// \brief Are we inside a macro instantiation?
265 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
266
267 /// \brief Handle entry to macro instantiation.
268 ///
269 /// \param M The macro.
270 /// \param NameLoc Instantiation location.
271 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
272
273 /// \brief Handle exit from macro instantiation.
274 void HandleMacroExit();
275
276 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
277 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
278 /// correct delimiter by the method.
279 bool ParseMacroArgument(MCAsmMacroArgument &MA,
280 AsmToken::TokenKind &ArgumentDelimiter);
281
282 /// \brief Parse all macro arguments for a given macro.
283 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
284
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000285 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000286 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000287 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
288 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000289 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000290 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000291
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000292 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
293 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000294 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
295 /// This returns true on failure.
296 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000297
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000298 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000299 /// current token is not set; clients should ensure Lex() is called
300 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000301 ///
302 /// \param InBuffer If not -1, should be the known buffer id that contains the
303 /// location.
304 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000305
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000306 /// \brief Parse up to the end of statement and a return the contents from the
307 /// current token until the end of the statement; the current token on exit
308 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000309 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000310
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000311 /// \brief Parse until the end of a statement or a comma is encountered,
312 /// return the contents from the current token up to the end or comma.
313 StringRef ParseStringToComma();
314
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000315 bool ParseAssignment(StringRef Name, bool allow_redef,
316 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000317
318 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
319 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
320 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000321 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000322
Eli Bendersky6ee13082013-01-15 22:59:42 +0000323 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000324
Eli Bendersky6ee13082013-01-15 22:59:42 +0000325 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000326 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000327 DK_NO_DIRECTIVE, // Placeholder
328 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
329 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
330 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000331 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000332 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
333 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
334 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
335 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
336 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
337 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
338 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000339 DK_ELSEIF, DK_ELSE, DK_ENDIF,
340 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
341 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
342 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
343 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
344 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
345 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
346 DK_CFI_REGISTER,
347 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
348 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000349 };
350
Eli Bendersky6ee13082013-01-15 22:59:42 +0000351 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
352 /// directives parsed by this class.
353 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000354
355 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000356 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000357 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000358 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000359 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000360 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000361 // ".set", ".equ", ".equiv"
362 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000363 bool ParseDirectiveOrg(); // ".org"
364 // ".align{,32}", ".p2align{,w,l}"
365 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
366
Eli Bendersky6ee13082013-01-15 22:59:42 +0000367 // ".file", ".line", ".loc", ".stabs"
368 bool ParseDirectiveFile(SMLoc DirectiveLoc);
369 bool ParseDirectiveLine();
370 bool ParseDirectiveLoc();
371 bool ParseDirectiveStabs();
372
373 // .cfi directives
374 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
375 bool ParseDirectiveCFISections();
376 bool ParseDirectiveCFIStartProc();
377 bool ParseDirectiveCFIEndProc();
378 bool ParseDirectiveCFIDefCfaOffset();
379 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIAdjustCfaOffset();
381 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
385 bool ParseDirectiveCFIRememberState();
386 bool ParseDirectiveCFIRestoreState();
387 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
388 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIEscape();
390 bool ParseDirectiveCFISignalFrame();
391 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
392
393 // macro directives
394 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveEndMacro(StringRef Directive);
396 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveMacrosOnOff(StringRef Directive);
398
Eli Bendersky4766ef42012-12-20 19:05:53 +0000399 // ".bundle_align_mode"
400 bool ParseDirectiveBundleAlignMode();
401 // ".bundle_lock"
402 bool ParseDirectiveBundleLock();
403 // ".bundle_unlock"
404 bool ParseDirectiveBundleUnlock();
405
Eli Bendersky6ee13082013-01-15 22:59:42 +0000406 // ".space", ".skip"
407 bool ParseDirectiveSpace(StringRef IDVal);
408
409 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
410 bool ParseDirectiveLEB128(bool Signed);
411
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000412 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
413 /// accepts a single symbol (which should be a label or an external).
414 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000415
416 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
417
418 bool ParseDirectiveAbort(); // ".abort"
419 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000420 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000421
422 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000423 // ".ifb" or ".ifnb", depending on ExpectBlank.
424 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000425 // ".ifc" or ".ifnc", depending on ExpectEqual.
426 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000427 // ".ifdef" or ".ifndef", depending on expect_defined
428 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000429 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
430 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
431 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Daniel Dunbarbfdcc702013-01-18 01:25:33 +0000432 virtual bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000433
434 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
435 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000436
Rafael Espindola761cb062012-06-03 23:57:14 +0000437 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000438 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
439 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000440 raw_svector_ostream &OS);
441 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000442 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000443 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000444 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000445
Eli Friedman2128aae2012-10-22 23:58:19 +0000446 // "_emit"
Chad Rosiere1d64032013-02-12 19:42:32 +0000447 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
448 size_t len);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000449
Eli Bendersky6ee13082013-01-15 22:59:42 +0000450 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000451};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000452}
453
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000454namespace llvm {
455
456extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000457extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000458extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459
460}
461
Chris Lattneraaec2052010-01-19 19:46:13 +0000462enum { DEFAULT_ADDRSPACE = 0 };
463
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000464AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000465 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000466 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000467 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000468 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000469 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000470 // Save the old handler.
471 SavedDiagHandler = SrcMgr.getDiagHandler();
472 SavedDiagContext = SrcMgr.getDiagContext();
473 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000474 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000475 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000476
Daniel Dunbare4749702010-07-12 18:12:02 +0000477 // Initialize the platform / file format parser.
478 //
479 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
480 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000481 if (_MAI.hasMicrosoftFastStdCallMangling()) {
482 PlatformParser = createCOFFAsmParser();
483 PlatformParser->Initialize(*this);
484 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000485 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000486 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000487 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000488 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000489 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000490 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000491 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000492
Eli Bendersky6ee13082013-01-15 22:59:42 +0000493 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000494}
495
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000496AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000497 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
498
499 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000500 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000501 ie = MacroMap.end(); it != ie; ++it)
502 delete it->getValue();
503
Daniel Dunbare4749702010-07-12 18:12:02 +0000504 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000505}
506
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000507void AsmParser::PrintMacroInstantiations() {
508 // Print the active macro instantiation stack.
509 for (std::vector<MacroInstantiation*>::const_reverse_iterator
510 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000511 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
512 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000513}
514
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000515bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000516 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000517 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000518 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000519 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000520 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000521}
522
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000523bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000524 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000525 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000526 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000527 return true;
528}
529
Sean Callananfd0b0282010-01-21 00:19:58 +0000530bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000531 std::string IncludedFile;
532 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 if (NewBuf == -1)
534 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000535
Sean Callananfd0b0282010-01-21 00:19:58 +0000536 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000537
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 return false;
541}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000542
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000543/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000544/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000545/// returns true on failure.
546bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
547 std::string IncludedFile;
548 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
549 if (NewBuf == -1)
550 return true;
551
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000552 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000553 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
554 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000555 return false;
556}
557
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000558void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
559 if (InBuffer != -1) {
560 CurBuffer = InBuffer;
561 } else {
562 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
563 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
565}
566
Sean Callananfd0b0282010-01-21 00:19:58 +0000567const AsmToken &AsmParser::Lex() {
568 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000569
Sean Callananfd0b0282010-01-21 00:19:58 +0000570 if (tok->is(AsmToken::Eof)) {
571 // If this is the end of an included file, pop the parent file off the
572 // include stack.
573 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
574 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000575 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000576 tok = &Lexer.Lex();
577 }
578 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000581 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000582
Sean Callananfd0b0282010-01-21 00:19:58 +0000583 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000584}
585
Chris Lattner79180e22010-04-05 23:15:42 +0000586bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000587 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000588 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000589 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000590
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000591 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000592 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000593
594 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000595 AsmCond StartingCondState = TheCondState;
596
Kevin Enderby613b7572011-11-01 22:27:22 +0000597 // If we are generating dwarf for assembly source files save the initial text
598 // section and generate a .file directive.
599 if (getContext().getGenDwarfForAssembly()) {
600 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000601 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
602 getStreamer().EmitLabel(SectionStartSym);
603 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000604 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000605 StringRef(),
606 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000607 }
608
Chris Lattnerb717fb02009-07-02 21:53:43 +0000609 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000610 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000611 ParseStatementInfo Info;
612 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000613
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000614 // We had an error, validate that one was emitted and recover by skipping to
615 // the next line.
616 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000617 EatToEndOfStatement();
618 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000619
620 if (TheCondState.TheCond != StartingCondState.TheCond ||
621 TheCondState.Ignore != StartingCondState.Ignore)
622 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000623
624 // Check to see there are no empty DwarfFile slots.
625 const std::vector<MCDwarfFile *> &MCDwarfFiles =
626 getContext().getMCDwarfFiles();
627 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000628 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000629 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000630 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000632 // Check to see that all assembler local symbols were actually defined.
633 // Targets that don't do subsections via symbols may not want this, though,
634 // so conservatively exclude them. Only do this if we're finalizing, though,
635 // as otherwise we won't necessarilly have seen everything yet.
636 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
637 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
638 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
639 e = Symbols.end();
640 i != e; ++i) {
641 MCSymbol *Sym = i->getValue();
642 // Variable symbols may not be marked as defined, so check those
643 // explicitly. If we know it's a variable, we have a definition for
644 // the purposes of this check.
645 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
646 // FIXME: We would really like to refer back to where the symbol was
647 // first referenced for a source location. We need to add something
648 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000649 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
650 "assembler local symbol '" + Sym->getName() +
651 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000652 }
653 }
654
655
Chris Lattner79180e22010-04-05 23:15:42 +0000656 // Finalize the output stream if there are no errors and if the client wants
657 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000658 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000659 Out.Finish();
660
Chris Lattnerb717fb02009-07-02 21:53:43 +0000661 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000662}
663
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000664void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000665 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000666 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000667 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000668 }
669}
670
Chris Lattner2cf5f142009-06-22 01:29:09 +0000671/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
672void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000673 while (Lexer.isNot(AsmToken::EndOfStatement) &&
674 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000676
Chris Lattner2cf5f142009-06-22 01:29:09 +0000677 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000678 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000679 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000680}
681
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000682StringRef AsmParser::ParseStringToEndOfStatement() {
683 const char *Start = getTok().getLoc().getPointer();
684
685 while (Lexer.isNot(AsmToken::EndOfStatement) &&
686 Lexer.isNot(AsmToken::Eof))
687 Lex();
688
689 const char *End = getTok().getLoc().getPointer();
690 return StringRef(Start, End - Start);
691}
Chris Lattnerc4193832009-06-22 05:51:26 +0000692
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000693StringRef AsmParser::ParseStringToComma() {
694 const char *Start = getTok().getLoc().getPointer();
695
696 while (Lexer.isNot(AsmToken::EndOfStatement) &&
697 Lexer.isNot(AsmToken::Comma) &&
698 Lexer.isNot(AsmToken::Eof))
699 Lex();
700
701 const char *End = getTok().getLoc().getPointer();
702 return StringRef(Start, End - Start);
703}
704
Chris Lattner74ec1a32009-06-22 06:32:03 +0000705/// ParseParenExpr - Parse a paren expression and return it.
706/// NOTE: This assumes the leading '(' has already been consumed.
707///
708/// parenexpr ::= expr)
709///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000710bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000711 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000712 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000713 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000714 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000715 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000716 return false;
717}
Chris Lattnerc4193832009-06-22 05:51:26 +0000718
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000719/// ParseBracketExpr - Parse a bracket expression and return it.
720/// NOTE: This assumes the leading '[' has already been consumed.
721///
722/// bracketexpr ::= expr]
723///
724bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (ParseExpression(Res)) return true;
726 if (Lexer.isNot(AsmToken::RBrac))
727 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000728 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000729 Lex();
730 return false;
731}
732
Chris Lattner74ec1a32009-06-22 06:32:03 +0000733/// ParsePrimaryExpr - Parse a primary expression and return it.
734/// primaryexpr ::= (parenexpr
735/// primaryexpr ::= symbol
736/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000737/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000738/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000739bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000740 SMLoc FirstTokenLoc = getLexer().getLoc();
741 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
742 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000743 default:
744 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000745 // If we have an error assume that we've already handled it.
746 case AsmToken::Error:
747 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000748 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000749 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000750 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000751 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000752 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000753 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000754 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000755 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000756 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000757 StringRef Identifier;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000758 if (ParseIdentifier(Identifier)) {
759 if (FirstTokenKind == AsmToken::Dollar)
760 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000761 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000762 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000763
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000764 EndLoc = SMLoc::getFromPointer(Identifier.end());
765
Daniel Dunbarfffff912009-10-16 01:34:54 +0000766 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000767 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000768 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000769
770 // Lookup the symbol variant if used.
771 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000772 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000773 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000774 if (Variant == MCSymbolRefExpr::VK_Invalid) {
775 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000776 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000777 }
778 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000779
Daniel Dunbarfffff912009-10-16 01:34:54 +0000780 // If this is an absolute variable reference, substitute it now to preserve
781 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000782 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000783 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000784 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000785
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000786 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000787 return false;
788 }
789
790 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000791 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000792 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000793 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000794 case AsmToken::Integer: {
795 SMLoc Loc = getTok().getLoc();
796 int64_t IntVal = getTok().getIntVal();
797 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000798 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000799 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000800 // Look for 'b' or 'f' following an Integer as a directional label
801 if (Lexer.getKind() == AsmToken::Identifier) {
802 StringRef IDVal = getTok().getString();
803 if (IDVal == "f" || IDVal == "b"){
804 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
805 IDVal == "f" ? 1 : 0);
806 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
807 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000808 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000809 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000810 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000811 Lex(); // Eat identifier.
812 }
813 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000814 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000815 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000816 case AsmToken::Real: {
817 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000818 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000819 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000820 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000821 Lex(); // Eat token.
822 return false;
823 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000824 case AsmToken::Dot: {
825 // This is a '.' reference, which references the current PC. Emit a
826 // temporary label to the streamer and refer to it.
827 MCSymbol *Sym = Ctx.CreateTempSymbol();
828 Out.EmitLabel(Sym);
829 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000830 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000831 Lex(); // Eat identifier.
832 return false;
833 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000834 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000835 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000836 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000837 case AsmToken::LBrac:
838 if (!PlatformParser->HasBracketExpressions())
839 return TokError("brackets expression not supported on this target");
840 Lex(); // Eat the '['.
841 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000842 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000843 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000844 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000845 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000846 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000847 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000848 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000849 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000850 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000851 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000852 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000853 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000854 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000855 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000856 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000857 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000858 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000859 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000860 }
861}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000862
Chris Lattnerb4307b32010-01-15 19:28:38 +0000863bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000864 SMLoc EndLoc;
865 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000866}
867
Daniel Dunbarcceba832010-09-17 02:47:07 +0000868const MCExpr *
869AsmParser::ApplyModifierToExpr(const MCExpr *E,
870 MCSymbolRefExpr::VariantKind Variant) {
871 // Recurse over the given expression, rebuilding it to apply the given variant
872 // if there is exactly one symbol.
873 switch (E->getKind()) {
874 case MCExpr::Target:
875 case MCExpr::Constant:
876 return 0;
877
878 case MCExpr::SymbolRef: {
879 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
880
881 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
882 TokError("invalid variant on expression '" +
883 getTok().getIdentifier() + "' (already modified)");
884 return E;
885 }
886
887 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
888 }
889
890 case MCExpr::Unary: {
891 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
892 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
893 if (!Sub)
894 return 0;
895 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
896 }
897
898 case MCExpr::Binary: {
899 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
900 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
901 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
902
903 if (!LHS && !RHS)
904 return 0;
905
906 if (!LHS) LHS = BE->getLHS();
907 if (!RHS) RHS = BE->getRHS();
908
909 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
910 }
911 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000912
Craig Topper85814382012-02-07 05:05:23 +0000913 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000914}
915
Chris Lattner74ec1a32009-06-22 06:32:03 +0000916/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000917///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000918/// expr ::= expr &&,|| expr -> lowest.
919/// expr ::= expr |,^,&,! expr
920/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
921/// expr ::= expr <<,>> expr
922/// expr ::= expr +,- expr
923/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000924/// expr ::= primaryexpr
925///
Chris Lattner54482b42010-01-15 19:39:23 +0000926bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000927 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000928 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000929 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
930 return true;
931
Daniel Dunbarcceba832010-09-17 02:47:07 +0000932 // As a special case, we support 'a op b @ modifier' by rewriting the
933 // expression to include the modifier. This is inefficient, but in general we
934 // expect users to use 'a@modifier op b'.
935 if (Lexer.getKind() == AsmToken::At) {
936 Lex();
937
938 if (Lexer.isNot(AsmToken::Identifier))
939 return TokError("unexpected symbol modifier following '@'");
940
941 MCSymbolRefExpr::VariantKind Variant =
942 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
943 if (Variant == MCSymbolRefExpr::VK_Invalid)
944 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
945
946 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
947 if (!ModifiedRes) {
948 return TokError("invalid modifier '" + getTok().getIdentifier() +
949 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000950 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000951
Daniel Dunbarcceba832010-09-17 02:47:07 +0000952 Res = ModifiedRes;
953 Lex();
954 }
955
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000956 // Try to constant fold it up front, if possible.
957 int64_t Value;
958 if (Res->EvaluateAsAbsolute(Value))
959 Res = MCConstantExpr::Create(Value, getContext());
960
961 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000962}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000963
Chris Lattnerb4307b32010-01-15 19:28:38 +0000964bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000965 Res = 0;
966 return ParseParenExpr(Res, EndLoc) ||
967 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000968}
969
Daniel Dunbar475839e2009-06-29 20:37:27 +0000970bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000971 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000972
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000973 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000974 if (ParseExpression(Expr))
975 return true;
976
Daniel Dunbare00b0112009-10-16 01:57:52 +0000977 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000978 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000979
980 return false;
981}
982
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000983static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000984 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000985 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000986 default:
987 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000988
Jim Grosbachfbe16812011-08-20 16:24:13 +0000989 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000990 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000991 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000992 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000993 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000994 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000995 return 1;
996
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000997
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000998 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000999 //
1000 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001001 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001002 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001003 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001004 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001005 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001006 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001007 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001008 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001009 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001010
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001011 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001012 case AsmToken::EqualEqual:
1013 Kind = MCBinaryExpr::EQ;
1014 return 3;
1015 case AsmToken::ExclaimEqual:
1016 case AsmToken::LessGreater:
1017 Kind = MCBinaryExpr::NE;
1018 return 3;
1019 case AsmToken::Less:
1020 Kind = MCBinaryExpr::LT;
1021 return 3;
1022 case AsmToken::LessEqual:
1023 Kind = MCBinaryExpr::LTE;
1024 return 3;
1025 case AsmToken::Greater:
1026 Kind = MCBinaryExpr::GT;
1027 return 3;
1028 case AsmToken::GreaterEqual:
1029 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001030 return 3;
1031
Jim Grosbachfbe16812011-08-20 16:24:13 +00001032 // Intermediate Precedence: <<, >>
1033 case AsmToken::LessLess:
1034 Kind = MCBinaryExpr::Shl;
1035 return 4;
1036 case AsmToken::GreaterGreater:
1037 Kind = MCBinaryExpr::Shr;
1038 return 4;
1039
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001040 // High Intermediate Precedence: +, -
1041 case AsmToken::Plus:
1042 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001043 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001044 case AsmToken::Minus:
1045 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001046 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001047
Jim Grosbachfbe16812011-08-20 16:24:13 +00001048 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001049 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001050 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001051 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001052 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001053 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001054 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001055 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001056 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001058 }
1059}
1060
1061
1062/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1063/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001064bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1065 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001066 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001067 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001068 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001069
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001070 // If the next token is lower precedence than we are allowed to eat, return
1071 // successfully with what we ate already.
1072 if (TokPrec < Precedence)
1073 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001074
Sean Callanan79ed1a82010-01-19 20:22:31 +00001075 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001076
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001077 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001078 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001079 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001080
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001081 // If BinOp binds less tightly with RHS than the operator after RHS, let
1082 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001083 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001084 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001085 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001086 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001087 }
1088
Daniel Dunbar475839e2009-06-29 20:37:27 +00001089 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001090 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001091 }
1092}
1093
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001094/// ParseStatement:
1095/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001096/// ::= Label* Directive ...Operands... EndOfStatement
1097/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001098bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001099 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001100 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001101 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001102 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001103 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001104
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001105 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001106 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001107 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001108 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001109 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001110 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001111 if (Lexer.is(AsmToken::Hash))
1112 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001113
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001114 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001115 if (Lexer.is(AsmToken::Integer)) {
1116 LocalLabelVal = getTok().getIntVal();
1117 if (LocalLabelVal < 0) {
1118 if (!TheCondState.Ignore)
1119 return TokError("unexpected token at start of statement");
1120 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001121 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001122 IDVal = getTok().getString();
1123 Lex(); // Consume the integer token to be used as an identifier token.
1124 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001125 if (!TheCondState.Ignore)
1126 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001127 }
1128 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001129 } else if (Lexer.is(AsmToken::Dot)) {
1130 // Treat '.' as a valid identifier in this context.
1131 Lex();
1132 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001133 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
1136 IDVal = "";
1137 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001138
Chris Lattner7834fac2010-04-17 18:14:27 +00001139 // Handle conditional assembly here before checking for skipping. We
1140 // have to do this so that .endif isn't skipped in a ".if 0" block for
1141 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001142 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001143 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001144 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001145 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1146 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001147 switch (DirKind) {
1148 default:
1149 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001150 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001152 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001153 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001154 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001155 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001156 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001157 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001158 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001159 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001160 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001161 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001162 case DK_IFNDEF:
1163 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001164 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001165 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001166 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001167 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001169 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 return ParseDirectiveEndIf(IDLoc);
1171 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001172
Eli Benderskyed5df012013-01-16 19:32:36 +00001173 // Ignore the statement if in the middle of inactive conditional
1174 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001175 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001176 EatToEndOfStatement();
1177 return false;
1178 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001179
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001180 // FIXME: Recurse on local labels?
1181
1182 // See what kind of statement we have.
1183 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001184 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001185 CheckForValidSection();
1186
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001187 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001188 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001189
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001190 // Diagnose attempt to use '.' as a label.
1191 if (IDVal == ".")
1192 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1193
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001194 // Diagnose attempt to use a variable as a label.
1195 //
1196 // FIXME: Diagnostics. Note the location of the definition as a label.
1197 // FIXME: This doesn't diagnose assignment to a symbol which has been
1198 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001199 MCSymbol *Sym;
1200 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001201 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001202 else
1203 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001204 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001205 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001206
Daniel Dunbar959fd882009-08-26 22:13:22 +00001207 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001208 if (!ParsingInlineAsm)
1209 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001210
Kevin Enderby94c2e852011-12-09 18:09:40 +00001211 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001212 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001213 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001214 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1215 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001216
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001217 // Consume any end of statement token, if present, to avoid spurious
1218 // AddBlankLine calls().
1219 if (Lexer.is(AsmToken::EndOfStatement)) {
1220 Lex();
1221 if (Lexer.is(AsmToken::Eof))
1222 return false;
1223 }
1224
Eli Friedman2128aae2012-10-22 23:58:19 +00001225 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001226 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001227
Daniel Dunbar3f872332009-07-28 16:08:33 +00001228 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001229 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001230 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001231
Nico Weber4c4c7322011-01-28 03:04:41 +00001232 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001233
1234 default: // Normal instruction or directive.
1235 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001236 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001237
1238 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001239 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001240 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1241 return HandleMacroEntry(M, IDLoc);
1242 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001243
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001244 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001245
1246 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001247 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001248 // There are several entities interested in parsing directives:
1249 //
1250 // 1. The target-specific assembly parser. Some directives are target
1251 // specific or may potentially behave differently on certain targets.
1252 // 2. Asm parser extensions. For example, platform-specific parsers
1253 // (like the ELF parser) register themselves as extensions.
1254 // 3. The generic directive parser implemented by this class. These are
1255 // all the directives that behave in a target and platform independent
1256 // manner, or at least have a default behavior that's shared between
1257 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001258
Eli Bendersky6ee13082013-01-15 22:59:42 +00001259 // First query the target-specific parser. It will return 'true' if it
1260 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001261 if (!getTargetParser().ParseDirective(ID))
1262 return false;
1263
Eli Bendersky6ee13082013-01-15 22:59:42 +00001264 // Next, check the extention directive map to see if any extension has
1265 // registered itself to parse this directive.
1266 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1267 ExtensionDirectiveMap.lookup(IDVal);
1268 if (Handler.first)
1269 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1270
1271 // Finally, if no one else is interested in this directive, it must be
1272 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001273 switch (DirKind) {
1274 default:
1275 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001276 case DK_SET:
1277 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001278 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001279 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001280 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001281 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_ASCIZ:
1284 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001285 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001286 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001287 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001288 case DK_SHORT:
1289 case DK_VALUE:
1290 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001291 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001292 case DK_LONG:
1293 case DK_INT:
1294 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_QUAD:
1297 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001299 case DK_SINGLE:
1300 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001301 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001302 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001303 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001304 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1306 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1307 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001309 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1310 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1311 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001312 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001314 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001315 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001316 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001321 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001322 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001324 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001325 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001326 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 EatToEndOfStatement(); // .extern is the default, ignore it.
1332 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_GLOBL:
1334 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001335 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001336 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001337 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001338 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001339 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001343 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001347 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001348 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001349 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001350 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_COMM:
1355 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001356 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001357 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001358 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001359 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_CODE16:
1366 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001382 case DK_SLEB128:
1383 return ParseDirectiveLEB128(true);
1384 case DK_ULEB128:
1385 return ParseDirectiveLEB128(false);
1386 case DK_SPACE:
1387 case DK_SKIP:
1388 return ParseDirectiveSpace(IDVal);
1389 case DK_FILE:
1390 return ParseDirectiveFile(IDLoc);
1391 case DK_LINE:
1392 return ParseDirectiveLine();
1393 case DK_LOC:
1394 return ParseDirectiveLoc();
1395 case DK_STABS:
1396 return ParseDirectiveStabs();
1397 case DK_CFI_SECTIONS:
1398 return ParseDirectiveCFISections();
1399 case DK_CFI_STARTPROC:
1400 return ParseDirectiveCFIStartProc();
1401 case DK_CFI_ENDPROC:
1402 return ParseDirectiveCFIEndProc();
1403 case DK_CFI_DEF_CFA:
1404 return ParseDirectiveCFIDefCfa(IDLoc);
1405 case DK_CFI_DEF_CFA_OFFSET:
1406 return ParseDirectiveCFIDefCfaOffset();
1407 case DK_CFI_ADJUST_CFA_OFFSET:
1408 return ParseDirectiveCFIAdjustCfaOffset();
1409 case DK_CFI_DEF_CFA_REGISTER:
1410 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1411 case DK_CFI_OFFSET:
1412 return ParseDirectiveCFIOffset(IDLoc);
1413 case DK_CFI_REL_OFFSET:
1414 return ParseDirectiveCFIRelOffset(IDLoc);
1415 case DK_CFI_PERSONALITY:
1416 return ParseDirectiveCFIPersonalityOrLsda(true);
1417 case DK_CFI_LSDA:
1418 return ParseDirectiveCFIPersonalityOrLsda(false);
1419 case DK_CFI_REMEMBER_STATE:
1420 return ParseDirectiveCFIRememberState();
1421 case DK_CFI_RESTORE_STATE:
1422 return ParseDirectiveCFIRestoreState();
1423 case DK_CFI_SAME_VALUE:
1424 return ParseDirectiveCFISameValue(IDLoc);
1425 case DK_CFI_RESTORE:
1426 return ParseDirectiveCFIRestore(IDLoc);
1427 case DK_CFI_ESCAPE:
1428 return ParseDirectiveCFIEscape();
1429 case DK_CFI_SIGNAL_FRAME:
1430 return ParseDirectiveCFISignalFrame();
1431 case DK_CFI_UNDEFINED:
1432 return ParseDirectiveCFIUndefined(IDLoc);
1433 case DK_CFI_REGISTER:
1434 return ParseDirectiveCFIRegister(IDLoc);
1435 case DK_MACROS_ON:
1436 case DK_MACROS_OFF:
1437 return ParseDirectiveMacrosOnOff(IDVal);
1438 case DK_MACRO:
1439 return ParseDirectiveMacro(IDLoc);
1440 case DK_ENDM:
1441 case DK_ENDMACRO:
1442 return ParseDirectiveEndMacro(IDVal);
1443 case DK_PURGEM:
1444 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001445 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001446
Jim Grosbach686c0182012-05-01 18:38:27 +00001447 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001448 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001449
Chad Rosierab9d2512013-02-12 19:31:23 +00001450 // _emit or __emit
1451 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit"))
Chad Rosiere1d64032013-02-12 19:42:32 +00001452 return ParseDirectiveEmit(IDLoc, Info, IDVal.size());
Eli Friedman2128aae2012-10-22 23:58:19 +00001453
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001454 CheckForValidSection();
1455
Chris Lattnera7f13542010-05-19 23:34:33 +00001456 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001457 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001458 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001459 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1460 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001461 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001462
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001463 // Dump the parsed representation, if requested.
1464 if (getShowParsedOperands()) {
1465 SmallString<256> Str;
1466 raw_svector_ostream OS(Str);
1467 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001468 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001469 if (i != 0)
1470 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001471 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001472 }
1473 OS << "]";
1474
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001475 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001476 }
1477
Kevin Enderby613b7572011-11-01 22:27:22 +00001478 // If we are generating dwarf for assembly source files and the current
1479 // section is the initial text section then generate a .loc directive for
1480 // the instruction.
1481 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001482 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001483
Eli Benderskyed5df012013-01-16 19:32:36 +00001484 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001485
Eli Benderskyed5df012013-01-16 19:32:36 +00001486 // If we previously parsed a cpp hash file line comment then make sure the
1487 // current Dwarf File is for the CppHashFilename if not then emit the
1488 // Dwarf File table for it and adjust the line number for the .loc.
1489 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1490 getContext().getMCDwarfFiles();
1491 if (CppHashFilename.size() != 0) {
1492 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001493 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001494 getStreamer().EmitDwarfFileDirective(
1495 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001496
Kevin Enderby32c1a822012-11-05 21:55:41 +00001497 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001498 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001499 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001500
Kevin Enderby613b7572011-11-01 22:27:22 +00001501 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001502 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001503 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001504 StringRef());
1505 }
1506
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001507 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001508 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001509 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001510 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1511 Info.ParsedOperands,
1512 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001513 ParsingInlineAsm);
1514 }
Chris Lattner98986712010-01-14 22:21:20 +00001515
Chris Lattnercbf8a982010-09-11 16:18:25 +00001516 // Don't skip the rest of the line, the instruction parser is responsible for
1517 // that.
1518 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001519}
Chris Lattner9a023f72009-06-24 04:43:34 +00001520
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001521/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1522/// since they may not be able to be tokenized to get to the end of line token.
1523void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001524 if (!Lexer.is(AsmToken::EndOfStatement))
1525 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001526 // Eat EOL.
1527 Lex();
1528}
1529
1530/// ParseCppHashLineFilenameComment as this:
1531/// ::= # number "filename"
1532/// or just as a full line comment if it doesn't have a number and a string.
1533bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1534 Lex(); // Eat the hash token.
1535
1536 if (getLexer().isNot(AsmToken::Integer)) {
1537 // Consume the line since in cases it is not a well-formed line directive,
1538 // as if were simply a full line comment.
1539 EatToEndOfLine();
1540 return false;
1541 }
1542
1543 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001544 Lex();
1545
1546 if (getLexer().isNot(AsmToken::String)) {
1547 EatToEndOfLine();
1548 return false;
1549 }
1550
1551 StringRef Filename = getTok().getString();
1552 // Get rid of the enclosing quotes.
1553 Filename = Filename.substr(1, Filename.size()-2);
1554
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001555 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1556 CppHashLoc = L;
1557 CppHashFilename = Filename;
1558 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001559 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001560
1561 // Ignore any trailing characters, they're just comment.
1562 EatToEndOfLine();
1563 return false;
1564}
1565
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001566/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001567/// for the Filename and LineNo if any in the diagnostic.
1568void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1569 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1570 raw_ostream &OS = errs();
1571
1572 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1573 const SMLoc &DiagLoc = Diag.getLoc();
1574 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1575 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1576
1577 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1578 // before printing the message.
1579 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001580 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001581 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1582 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1583 }
1584
Eric Christopher2318ba12012-12-18 00:30:54 +00001585 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001586 // manager changed or buffer changed (like in a nested include) then just
1587 // print the normal diagnostic using its Filename and LineNo.
1588 if (!Parser->CppHashLineNumber ||
1589 &DiagSrcMgr != &Parser->SrcMgr ||
1590 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001591 if (Parser->SavedDiagHandler)
1592 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1593 else
1594 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001595 return;
1596 }
1597
Eric Christopher2318ba12012-12-18 00:30:54 +00001598 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001599 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1600 // the diagnostic.
1601 const std::string Filename = Parser->CppHashFilename;
1602
1603 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1604 int CppHashLocLineNo =
1605 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1606 int LineNo = Parser->CppHashLineNumber - 1 +
1607 (DiagLocLineNo - CppHashLocLineNo);
1608
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001609 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1610 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001611 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001612 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001613
Benjamin Kramer04a04262011-10-16 10:48:29 +00001614 if (Parser->SavedDiagHandler)
1615 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1616 else
1617 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001618}
1619
Rafael Espindola799aacf2012-08-21 18:29:30 +00001620// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1621// difference being that that function accepts '@' as part of identifiers and
1622// we can't do that. AsmLexer.cpp should probably be changed to handle
1623// '@' as a special case when needed.
1624static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001625 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1626 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001627}
1628
Rafael Espindola761cb062012-06-03 23:57:14 +00001629bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001630 const MCAsmMacroParameters &Parameters,
1631 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001632 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001633 unsigned NParameters = Parameters.size();
1634 if (NParameters != 0 && NParameters != A.size())
1635 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001636
Preston Gurd7b6f2032012-09-19 20:36:12 +00001637 // A macro without parameters is handled differently on Darwin:
1638 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001639 while (!Body.empty()) {
1640 // Scan for the next substitution.
1641 std::size_t End = Body.size(), Pos = 0;
1642 for (; Pos != End; ++Pos) {
1643 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001644 if (!NParameters) {
1645 // This macro has no parameters, look for $0, $1, etc.
1646 if (Body[Pos] != '$' || Pos + 1 == End)
1647 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001648
Rafael Espindola65366442011-06-05 02:43:45 +00001649 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001650 if (Next == '$' || Next == 'n' ||
1651 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001652 break;
1653 } else {
1654 // This macro has parameters, look for \foo, \bar, etc.
1655 if (Body[Pos] == '\\' && Pos + 1 != End)
1656 break;
1657 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001658 }
1659
1660 // Add the prefix.
1661 OS << Body.slice(0, Pos);
1662
1663 // Check if we reached the end.
1664 if (Pos == End)
1665 break;
1666
Rafael Espindola65366442011-06-05 02:43:45 +00001667 if (!NParameters) {
1668 switch (Body[Pos+1]) {
1669 // $$ => $
1670 case '$':
1671 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001672 break;
1673
Rafael Espindola65366442011-06-05 02:43:45 +00001674 // $n => number of arguments
1675 case 'n':
1676 OS << A.size();
1677 break;
1678
1679 // $[0-9] => argument
1680 default: {
1681 // Missing arguments are ignored.
1682 unsigned Index = Body[Pos+1] - '0';
1683 if (Index >= A.size())
1684 break;
1685
1686 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001687 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001688 ie = A[Index].end(); it != ie; ++it)
1689 OS << it->getString();
1690 break;
1691 }
1692 }
1693 Pos += 2;
1694 } else {
1695 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001696 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001697 ++I;
1698
1699 const char *Begin = Body.data() + Pos +1;
1700 StringRef Argument(Begin, I - (Pos +1));
1701 unsigned Index = 0;
1702 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001703 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001704 break;
1705
Preston Gurd7b6f2032012-09-19 20:36:12 +00001706 if (Index == NParameters) {
1707 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1708 Pos += 3;
1709 else {
1710 OS << '\\' << Argument;
1711 Pos = I;
1712 }
1713 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001714 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001715 ie = A[Index].end(); it != ie; ++it)
1716 if (it->getKind() == AsmToken::String)
1717 OS << it->getStringContents();
1718 else
1719 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001720
Preston Gurd7b6f2032012-09-19 20:36:12 +00001721 Pos += 1 + Argument.size();
1722 }
Rafael Espindola65366442011-06-05 02:43:45 +00001723 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001724 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001725 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001726 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001727
Rafael Espindola65366442011-06-05 02:43:45 +00001728 return false;
1729}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001730
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001731MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001732 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001733 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001734 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1735 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001736{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001737}
1738
Preston Gurd7b6f2032012-09-19 20:36:12 +00001739static bool IsOperator(AsmToken::TokenKind kind)
1740{
1741 switch (kind)
1742 {
1743 default:
1744 return false;
1745 case AsmToken::Plus:
1746 case AsmToken::Minus:
1747 case AsmToken::Tilde:
1748 case AsmToken::Slash:
1749 case AsmToken::Star:
1750 case AsmToken::Dot:
1751 case AsmToken::Equal:
1752 case AsmToken::EqualEqual:
1753 case AsmToken::Pipe:
1754 case AsmToken::PipePipe:
1755 case AsmToken::Caret:
1756 case AsmToken::Amp:
1757 case AsmToken::AmpAmp:
1758 case AsmToken::Exclaim:
1759 case AsmToken::ExclaimEqual:
1760 case AsmToken::Percent:
1761 case AsmToken::Less:
1762 case AsmToken::LessEqual:
1763 case AsmToken::LessLess:
1764 case AsmToken::LessGreater:
1765 case AsmToken::Greater:
1766 case AsmToken::GreaterEqual:
1767 case AsmToken::GreaterGreater:
1768 return true;
1769 }
1770}
1771
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001772bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001773 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001774 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001775 unsigned AddTokens = 0;
1776
1777 // gas accepts arguments separated by whitespace, except on Darwin
1778 if (!IsDarwin)
1779 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001780
1781 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001782 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1783 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001784 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001785 }
1786
1787 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1788 // Spaces and commas cannot be mixed to delimit parameters
1789 if (ArgumentDelimiter == AsmToken::Eof)
1790 ArgumentDelimiter = AsmToken::Comma;
1791 else if (ArgumentDelimiter != AsmToken::Comma) {
1792 Lexer.setSkipSpace(true);
1793 return TokError("expected ' ' for macro argument separator");
1794 }
1795 break;
1796 }
1797
1798 if (Lexer.is(AsmToken::Space)) {
1799 Lex(); // Eat spaces
1800
1801 // Spaces can delimit parameters, but could also be part an expression.
1802 // If the token after a space is an operator, add the token and the next
1803 // one into this argument
1804 if (ArgumentDelimiter == AsmToken::Space ||
1805 ArgumentDelimiter == AsmToken::Eof) {
1806 if (IsOperator(Lexer.getKind())) {
1807 // Check to see whether the token is used as an operator,
1808 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001809 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001810 if (*NextChar == ' ')
1811 AddTokens = 2;
1812 }
1813
1814 if (!AddTokens && ParenLevel == 0) {
1815 if (ArgumentDelimiter == AsmToken::Eof &&
1816 !IsOperator(Lexer.getKind()))
1817 ArgumentDelimiter = AsmToken::Space;
1818 break;
1819 }
1820 }
1821 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001822
1823 // HandleMacroEntry relies on not advancing the lexer here
1824 // to be able to fill in the remaining default parameter values
1825 if (Lexer.is(AsmToken::EndOfStatement))
1826 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001827
1828 // Adjust the current parentheses level.
1829 if (Lexer.is(AsmToken::LParen))
1830 ++ParenLevel;
1831 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1832 --ParenLevel;
1833
1834 // Append the token to the current argument list.
1835 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001836 if (AddTokens)
1837 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001838 Lex();
1839 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001840
1841 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001842 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001843 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001844 return false;
1845}
1846
1847// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001848bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001849 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001850 // Argument delimiter is initially unknown. It will be set by
1851 // ParseMacroArgument()
1852 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001853
1854 // Parse two kinds of macro invocations:
1855 // - macros defined without any parameters accept an arbitrary number of them
1856 // - macros defined with parameters accept at most that many of them
1857 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1858 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001859 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001860
Preston Gurd7b6f2032012-09-19 20:36:12 +00001861 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001862 return true;
1863
Preston Gurd6c9176a2012-09-19 20:29:04 +00001864 if (!MA.empty() || !NParameters)
1865 A.push_back(MA);
1866 else if (NParameters) {
1867 if (!M->Parameters[Parameter].second.empty())
1868 A.push_back(M->Parameters[Parameter].second);
1869 }
Jim Grosbach97146442012-07-30 22:44:17 +00001870
Preston Gurd6c9176a2012-09-19 20:29:04 +00001871 // At the end of the statement, fill in remaining arguments that have
1872 // default values. If there aren't any, then the next argument is
1873 // required but missing
1874 if (Lexer.is(AsmToken::EndOfStatement)) {
1875 if (NParameters && Parameter < NParameters - 1) {
1876 if (M->Parameters[Parameter + 1].second.empty())
1877 return TokError("macro argument '" +
1878 Twine(M->Parameters[Parameter + 1].first) +
1879 "' is missing");
1880 else
1881 continue;
1882 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001883 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001884 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001885
1886 if (Lexer.is(AsmToken::Comma))
1887 Lex();
1888 }
1889 return TokError("Too many arguments");
1890}
1891
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001892const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1893 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1894 return (I == MacroMap.end()) ? NULL : I->getValue();
1895}
1896
1897void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1898 MacroMap[Name] = new MCAsmMacro(Macro);
1899}
1900
1901void AsmParser::UndefineMacro(StringRef Name) {
1902 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1903 if (I != MacroMap.end()) {
1904 delete I->getValue();
1905 MacroMap.erase(I);
1906 }
1907}
1908
1909bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001910 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1911 // this, although we should protect against infinite loops.
1912 if (ActiveMacros.size() == 20)
1913 return TokError("macros cannot be nested more than 20 levels deep");
1914
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001915 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001916 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001917 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001918
Jim Grosbach97146442012-07-30 22:44:17 +00001919 // Remove any trailing empty arguments. Do this after-the-fact as we have
1920 // to keep empty arguments in the middle of the list or positionality
1921 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001922 while (!A.empty() && A.back().empty())
1923 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001924
Rafael Espindola65366442011-06-05 02:43:45 +00001925 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1926 // to hold the macro body with substitutions.
1927 SmallString<256> Buf;
1928 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001929 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001930
Rafael Espindola8a403d32012-08-08 14:51:03 +00001931 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001932 return true;
1933
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001934 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001935 // instantiation.
1936 OS << ".endmacro\n";
1937
Rafael Espindola65366442011-06-05 02:43:45 +00001938 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001939 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001940
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001941 // Create the macro instantiation object and add to the current macro
1942 // instantiation stack.
1943 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001944 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001945 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001946 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001947 ActiveMacros.push_back(MI);
1948
1949 // Jump to the macro instantiation and prime the lexer.
1950 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1951 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1952 Lex();
1953
1954 return false;
1955}
1956
1957void AsmParser::HandleMacroExit() {
1958 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001959 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001960 Lex();
1961
1962 // Pop the instantiation entry.
1963 delete ActiveMacros.back();
1964 ActiveMacros.pop_back();
1965}
1966
Rafael Espindolae71cc862012-01-28 05:57:00 +00001967static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001968 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001969 case MCExpr::Binary: {
1970 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1971 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001972 break;
1973 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001974 case MCExpr::Target:
1975 case MCExpr::Constant:
1976 return false;
1977 case MCExpr::SymbolRef: {
1978 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001979 if (S.isVariable())
1980 return IsUsedIn(Sym, S.getVariableValue());
1981 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001982 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001983 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001984 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001985 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001986
1987 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001988}
1989
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001990bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1991 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001992 // FIXME: Use better location, we should use proper tokens.
1993 SMLoc EqualLoc = Lexer.getLoc();
1994
Daniel Dunbar821e3332009-08-31 08:09:28 +00001995 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001996 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001997 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001998
Rafael Espindolae71cc862012-01-28 05:57:00 +00001999 // Note: we don't count b as used in "a = b". This is to allow
2000 // a = b
2001 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002002
Daniel Dunbar3f872332009-07-28 16:08:33 +00002003 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002004 return TokError("unexpected token in assignment");
2005
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002006 // Error on assignment to '.'.
2007 if (Name == ".") {
2008 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2009 "(use '.space' or '.org').)"));
2010 }
2011
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002012 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002013 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002014
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002015 // Validate that the LHS is allowed to be a variable (either it has not been
2016 // used as a symbol, or it is an absolute symbol).
2017 MCSymbol *Sym = getContext().LookupSymbol(Name);
2018 if (Sym) {
2019 // Diagnose assignment to a label.
2020 //
2021 // FIXME: Diagnostics. Note the location of the definition as a label.
2022 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002023 if (IsUsedIn(Sym, Value))
2024 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2025 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002026 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002027 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2028 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002029 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002030 return Error(EqualLoc, "redefinition of '" + Name + "'");
2031 else if (!Sym->isVariable())
2032 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002033 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002034 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2035 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002036
2037 // Don't count these checks as uses.
2038 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002039 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002040 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002041
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002042 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002043
2044 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002045 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002046 if (NoDeadStrip)
2047 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2048
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002049
2050 return false;
2051}
2052
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002053/// ParseIdentifier:
2054/// ::= identifier
2055/// ::= string
2056bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002057 // The assembler has relaxed rules for accepting identifiers, in particular we
2058 // allow things like '.globl $foo', which would normally be separate
2059 // tokens. At this level, we have already lexed so we cannot (currently)
2060 // handle this as a context dependent token, instead we detect adjacent tokens
2061 // and return the combined identifier.
2062 if (Lexer.is(AsmToken::Dollar)) {
2063 SMLoc DollarLoc = getLexer().getLoc();
2064
2065 // Consume the dollar sign, and check for a following identifier.
2066 Lex();
2067 if (Lexer.isNot(AsmToken::Identifier))
2068 return true;
2069
2070 // We have a '$' followed by an identifier, make sure they are adjacent.
2071 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2072 return true;
2073
2074 // Construct the joined identifier and consume the token.
2075 Res = StringRef(DollarLoc.getPointer(),
2076 getTok().getIdentifier().size() + 1);
2077 Lex();
2078 return false;
2079 }
2080
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002081 if (Lexer.isNot(AsmToken::Identifier) &&
2082 Lexer.isNot(AsmToken::String))
2083 return true;
2084
Sean Callanan18b83232010-01-19 21:44:56 +00002085 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002086
Sean Callanan79ed1a82010-01-19 20:22:31 +00002087 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002088
2089 return false;
2090}
2091
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002092/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002093/// ::= .equ identifier ',' expression
2094/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002095/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002096bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002097 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002098
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002099 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002100 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002101
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002102 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002103 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002104 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002105
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002106 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002107}
2108
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002109bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002110 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002111
2112 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002113 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002114 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2115 if (Str[i] != '\\') {
2116 Data += Str[i];
2117 continue;
2118 }
2119
2120 // Recognize escaped characters. Note that this escape semantics currently
2121 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2122 ++i;
2123 if (i == e)
2124 return TokError("unexpected backslash at end of string");
2125
2126 // Recognize octal sequences.
2127 if ((unsigned) (Str[i] - '0') <= 7) {
2128 // Consume up to three octal characters.
2129 unsigned Value = Str[i] - '0';
2130
2131 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2132 ++i;
2133 Value = Value * 8 + (Str[i] - '0');
2134
2135 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2136 ++i;
2137 Value = Value * 8 + (Str[i] - '0');
2138 }
2139 }
2140
2141 if (Value > 255)
2142 return TokError("invalid octal escape sequence (out of range)");
2143
2144 Data += (unsigned char) Value;
2145 continue;
2146 }
2147
2148 // Otherwise recognize individual escapes.
2149 switch (Str[i]) {
2150 default:
2151 // Just reject invalid escape sequences for now.
2152 return TokError("invalid escape sequence (unrecognized character)");
2153
2154 case 'b': Data += '\b'; break;
2155 case 'f': Data += '\f'; break;
2156 case 'n': Data += '\n'; break;
2157 case 'r': Data += '\r'; break;
2158 case 't': Data += '\t'; break;
2159 case '"': Data += '"'; break;
2160 case '\\': Data += '\\'; break;
2161 }
2162 }
2163
2164 return false;
2165}
2166
Daniel Dunbara0d14262009-06-24 23:30:00 +00002167/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002168/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2169bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002170 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002171 CheckForValidSection();
2172
Daniel Dunbara0d14262009-06-24 23:30:00 +00002173 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002174 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002175 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002176
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002177 std::string Data;
2178 if (ParseEscapedString(Data))
2179 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002180
2181 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002182 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2184
Sean Callanan79ed1a82010-01-19 20:22:31 +00002185 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002186
2187 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002188 break;
2189
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002190 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002191 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002192 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002193 }
2194 }
2195
Sean Callanan79ed1a82010-01-19 20:22:31 +00002196 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002197 return false;
2198}
2199
2200/// ParseDirectiveValue
2201/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2202bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002203 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002204 CheckForValidSection();
2205
Daniel Dunbara0d14262009-06-24 23:30:00 +00002206 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002207 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002208 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002209 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002210 return true;
2211
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002212 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002213 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2214 assert(Size <= 8 && "Invalid size");
2215 uint64_t IntValue = MCE->getValue();
2216 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2217 return Error(ExprLoc, "literal value out of range for directive");
2218 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2219 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002220 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002222 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002223 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002224
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002226 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002228 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002229 }
2230 }
2231
Sean Callanan79ed1a82010-01-19 20:22:31 +00002232 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233 return false;
2234}
2235
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002236/// ParseDirectiveRealValue
2237/// ::= (.single | .double) [ expression (, expression)* ]
2238bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2239 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2240 CheckForValidSection();
2241
2242 for (;;) {
2243 // We don't truly support arithmetic on floating point expressions, so we
2244 // have to manually parse unary prefixes.
2245 bool IsNeg = false;
2246 if (getLexer().is(AsmToken::Minus)) {
2247 Lex();
2248 IsNeg = true;
2249 } else if (getLexer().is(AsmToken::Plus))
2250 Lex();
2251
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002252 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002253 getLexer().isNot(AsmToken::Real) &&
2254 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002255 return TokError("unexpected token in directive");
2256
2257 // Convert to an APFloat.
2258 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002259 StringRef IDVal = getTok().getString();
2260 if (getLexer().is(AsmToken::Identifier)) {
2261 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2262 Value = APFloat::getInf(Semantics);
2263 else if (!IDVal.compare_lower("nan"))
2264 Value = APFloat::getNaN(Semantics, false, ~0);
2265 else
2266 return TokError("invalid floating point literal");
2267 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002268 APFloat::opInvalidOp)
2269 return TokError("invalid floating point literal");
2270 if (IsNeg)
2271 Value.changeSign();
2272
2273 // Consume the numeric token.
2274 Lex();
2275
2276 // Emit the value as an integer.
2277 APInt AsInt = Value.bitcastToAPInt();
2278 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2279 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2280
2281 if (getLexer().is(AsmToken::EndOfStatement))
2282 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002283
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002284 if (getLexer().isNot(AsmToken::Comma))
2285 return TokError("unexpected token in directive");
2286 Lex();
2287 }
2288 }
2289
2290 Lex();
2291 return false;
2292}
2293
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002294/// ParseDirectiveZero
2295/// ::= .zero expression
2296bool AsmParser::ParseDirectiveZero() {
2297 CheckForValidSection();
2298
2299 int64_t NumBytes;
2300 if (ParseAbsoluteExpression(NumBytes))
2301 return true;
2302
Rafael Espindolae452b172010-10-05 19:42:57 +00002303 int64_t Val = 0;
2304 if (getLexer().is(AsmToken::Comma)) {
2305 Lex();
2306 if (ParseAbsoluteExpression(Val))
2307 return true;
2308 }
2309
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002310 if (getLexer().isNot(AsmToken::EndOfStatement))
2311 return TokError("unexpected token in '.zero' directive");
2312
2313 Lex();
2314
Rafael Espindolae452b172010-10-05 19:42:57 +00002315 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002316
2317 return false;
2318}
2319
Daniel Dunbara0d14262009-06-24 23:30:00 +00002320/// ParseDirectiveFill
2321/// ::= .fill expression , expression , expression
2322bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002323 CheckForValidSection();
2324
Daniel Dunbara0d14262009-06-24 23:30:00 +00002325 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002326 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002327 return true;
2328
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002329 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002330 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002331 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002332
Daniel Dunbara0d14262009-06-24 23:30:00 +00002333 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002334 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002335 return true;
2336
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002337 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002338 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002339 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002340
Daniel Dunbara0d14262009-06-24 23:30:00 +00002341 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002342 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002343 return true;
2344
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002345 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002346 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002347
Sean Callanan79ed1a82010-01-19 20:22:31 +00002348 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002349
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002350 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2351 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002352
2353 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002354 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002355
2356 return false;
2357}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002358
2359/// ParseDirectiveOrg
2360/// ::= .org expression [ , expression ]
2361bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002362 CheckForValidSection();
2363
Daniel Dunbar821e3332009-08-31 08:09:28 +00002364 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002365 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002366 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002367 return true;
2368
2369 // Parse optional fill expression.
2370 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002371 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2372 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002373 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002374 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002375
Daniel Dunbar475839e2009-06-29 20:37:27 +00002376 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002377 return true;
2378
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002379 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002380 return TokError("unexpected token in '.org' directive");
2381 }
2382
Sean Callanan79ed1a82010-01-19 20:22:31 +00002383 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002384
Jim Grosbachebd4c052012-01-27 00:37:08 +00002385 // Only limited forms of relocatable expressions are accepted here, it
2386 // has to be relative to the current section. The streamer will return
2387 // 'true' if the expression wasn't evaluatable.
2388 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2389 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002390
2391 return false;
2392}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002393
2394/// ParseDirectiveAlign
2395/// ::= {.align, ...} expression [ , expression [ , expression ]]
2396bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002397 CheckForValidSection();
2398
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002399 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002400 int64_t Alignment;
2401 if (ParseAbsoluteExpression(Alignment))
2402 return true;
2403
2404 SMLoc MaxBytesLoc;
2405 bool HasFillExpr = false;
2406 int64_t FillExpr = 0;
2407 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002408 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2409 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002410 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002411 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002412
2413 // The fill expression can be omitted while specifying a maximum number of
2414 // alignment bytes, e.g:
2415 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002416 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002417 HasFillExpr = true;
2418 if (ParseAbsoluteExpression(FillExpr))
2419 return true;
2420 }
2421
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2423 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002424 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002425 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002427 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002428 if (ParseAbsoluteExpression(MaxBytesToFill))
2429 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002430
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002431 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002432 return TokError("unexpected token in directive");
2433 }
2434 }
2435
Sean Callanan79ed1a82010-01-19 20:22:31 +00002436 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002437
Daniel Dunbar648ac512010-05-17 21:54:30 +00002438 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002439 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002440
2441 // Compute alignment in bytes.
2442 if (IsPow2) {
2443 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002444 if (Alignment >= 32) {
2445 Error(AlignmentLoc, "invalid alignment value");
2446 Alignment = 31;
2447 }
2448
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002449 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002450 }
2451
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002452 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002453 if (MaxBytesLoc.isValid()) {
2454 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002455 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2456 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002457 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458 }
2459
2460 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002461 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2462 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002463 MaxBytesToFill = 0;
2464 }
2465 }
2466
Daniel Dunbar648ac512010-05-17 21:54:30 +00002467 // Check whether we should use optimal code alignment for this .align
2468 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002469 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002470 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2471 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002472 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002473 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002474 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002475 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2476 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002477 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002478
2479 return false;
2480}
2481
Eli Bendersky6ee13082013-01-15 22:59:42 +00002482/// ParseDirectiveFile
2483/// ::= .file [number] filename
2484/// ::= .file number directory filename
2485bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2486 // FIXME: I'm not sure what this is.
2487 int64_t FileNumber = -1;
2488 SMLoc FileNumberLoc = getLexer().getLoc();
2489 if (getLexer().is(AsmToken::Integer)) {
2490 FileNumber = getTok().getIntVal();
2491 Lex();
2492
2493 if (FileNumber < 1)
2494 return TokError("file number less than one");
2495 }
2496
2497 if (getLexer().isNot(AsmToken::String))
2498 return TokError("unexpected token in '.file' directive");
2499
2500 // Usually the directory and filename together, otherwise just the directory.
2501 StringRef Path = getTok().getString();
2502 Path = Path.substr(1, Path.size()-2);
2503 Lex();
2504
2505 StringRef Directory;
2506 StringRef Filename;
2507 if (getLexer().is(AsmToken::String)) {
2508 if (FileNumber == -1)
2509 return TokError("explicit path specified, but no file number");
2510 Filename = getTok().getString();
2511 Filename = Filename.substr(1, Filename.size()-2);
2512 Directory = Path;
2513 Lex();
2514 } else {
2515 Filename = Path;
2516 }
2517
2518 if (getLexer().isNot(AsmToken::EndOfStatement))
2519 return TokError("unexpected token in '.file' directive");
2520
2521 if (FileNumber == -1)
2522 getStreamer().EmitFileDirective(Filename);
2523 else {
2524 if (getContext().getGenDwarfForAssembly() == true)
2525 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2526 "used to generate dwarf debug info for assembly code");
2527
2528 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2529 Error(FileNumberLoc, "file number already allocated");
2530 }
2531
2532 return false;
2533}
2534
2535/// ParseDirectiveLine
2536/// ::= .line [number]
2537bool AsmParser::ParseDirectiveLine() {
2538 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2539 if (getLexer().isNot(AsmToken::Integer))
2540 return TokError("unexpected token in '.line' directive");
2541
2542 int64_t LineNumber = getTok().getIntVal();
2543 (void) LineNumber;
2544 Lex();
2545
2546 // FIXME: Do something with the .line.
2547 }
2548
2549 if (getLexer().isNot(AsmToken::EndOfStatement))
2550 return TokError("unexpected token in '.line' directive");
2551
2552 return false;
2553}
2554
2555/// ParseDirectiveLoc
2556/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2557/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2558/// The first number is a file number, must have been previously assigned with
2559/// a .file directive, the second number is the line number and optionally the
2560/// third number is a column position (zero if not specified). The remaining
2561/// optional items are .loc sub-directives.
2562bool AsmParser::ParseDirectiveLoc() {
2563 if (getLexer().isNot(AsmToken::Integer))
2564 return TokError("unexpected token in '.loc' directive");
2565 int64_t FileNumber = getTok().getIntVal();
2566 if (FileNumber < 1)
2567 return TokError("file number less than one in '.loc' directive");
2568 if (!getContext().isValidDwarfFileNumber(FileNumber))
2569 return TokError("unassigned file number in '.loc' directive");
2570 Lex();
2571
2572 int64_t LineNumber = 0;
2573 if (getLexer().is(AsmToken::Integer)) {
2574 LineNumber = getTok().getIntVal();
2575 if (LineNumber < 1)
2576 return TokError("line number less than one in '.loc' directive");
2577 Lex();
2578 }
2579
2580 int64_t ColumnPos = 0;
2581 if (getLexer().is(AsmToken::Integer)) {
2582 ColumnPos = getTok().getIntVal();
2583 if (ColumnPos < 0)
2584 return TokError("column position less than zero in '.loc' directive");
2585 Lex();
2586 }
2587
2588 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2589 unsigned Isa = 0;
2590 int64_t Discriminator = 0;
2591 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2592 for (;;) {
2593 if (getLexer().is(AsmToken::EndOfStatement))
2594 break;
2595
2596 StringRef Name;
2597 SMLoc Loc = getTok().getLoc();
2598 if (ParseIdentifier(Name))
2599 return TokError("unexpected token in '.loc' directive");
2600
2601 if (Name == "basic_block")
2602 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2603 else if (Name == "prologue_end")
2604 Flags |= DWARF2_FLAG_PROLOGUE_END;
2605 else if (Name == "epilogue_begin")
2606 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2607 else if (Name == "is_stmt") {
2608 Loc = getTok().getLoc();
2609 const MCExpr *Value;
2610 if (ParseExpression(Value))
2611 return true;
2612 // The expression must be the constant 0 or 1.
2613 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2614 int Value = MCE->getValue();
2615 if (Value == 0)
2616 Flags &= ~DWARF2_FLAG_IS_STMT;
2617 else if (Value == 1)
2618 Flags |= DWARF2_FLAG_IS_STMT;
2619 else
2620 return Error(Loc, "is_stmt value not 0 or 1");
2621 }
2622 else {
2623 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2624 }
2625 }
2626 else if (Name == "isa") {
2627 Loc = getTok().getLoc();
2628 const MCExpr *Value;
2629 if (ParseExpression(Value))
2630 return true;
2631 // The expression must be a constant greater or equal to 0.
2632 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2633 int Value = MCE->getValue();
2634 if (Value < 0)
2635 return Error(Loc, "isa number less than zero");
2636 Isa = Value;
2637 }
2638 else {
2639 return Error(Loc, "isa number not a constant value");
2640 }
2641 }
2642 else if (Name == "discriminator") {
2643 if (ParseAbsoluteExpression(Discriminator))
2644 return true;
2645 }
2646 else {
2647 return Error(Loc, "unknown sub-directive in '.loc' directive");
2648 }
2649
2650 if (getLexer().is(AsmToken::EndOfStatement))
2651 break;
2652 }
2653 }
2654
2655 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2656 Isa, Discriminator, StringRef());
2657
2658 return false;
2659}
2660
2661/// ParseDirectiveStabs
2662/// ::= .stabs string, number, number, number
2663bool AsmParser::ParseDirectiveStabs() {
2664 return TokError("unsupported directive '.stabs'");
2665}
2666
2667/// ParseDirectiveCFISections
2668/// ::= .cfi_sections section [, section]
2669bool AsmParser::ParseDirectiveCFISections() {
2670 StringRef Name;
2671 bool EH = false;
2672 bool Debug = false;
2673
2674 if (ParseIdentifier(Name))
2675 return TokError("Expected an identifier");
2676
2677 if (Name == ".eh_frame")
2678 EH = true;
2679 else if (Name == ".debug_frame")
2680 Debug = true;
2681
2682 if (getLexer().is(AsmToken::Comma)) {
2683 Lex();
2684
2685 if (ParseIdentifier(Name))
2686 return TokError("Expected an identifier");
2687
2688 if (Name == ".eh_frame")
2689 EH = true;
2690 else if (Name == ".debug_frame")
2691 Debug = true;
2692 }
2693
2694 getStreamer().EmitCFISections(EH, Debug);
2695 return false;
2696}
2697
2698/// ParseDirectiveCFIStartProc
2699/// ::= .cfi_startproc
2700bool AsmParser::ParseDirectiveCFIStartProc() {
2701 getStreamer().EmitCFIStartProc();
2702 return false;
2703}
2704
2705/// ParseDirectiveCFIEndProc
2706/// ::= .cfi_endproc
2707bool AsmParser::ParseDirectiveCFIEndProc() {
2708 getStreamer().EmitCFIEndProc();
2709 return false;
2710}
2711
2712/// ParseRegisterOrRegisterNumber - parse register name or number.
2713bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2714 SMLoc DirectiveLoc) {
2715 unsigned RegNo;
2716
2717 if (getLexer().isNot(AsmToken::Integer)) {
2718 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2719 return true;
2720 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2721 } else
2722 return ParseAbsoluteExpression(Register);
2723
2724 return false;
2725}
2726
2727/// ParseDirectiveCFIDefCfa
2728/// ::= .cfi_def_cfa register, offset
2729bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2730 int64_t Register = 0;
2731 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2732 return true;
2733
2734 if (getLexer().isNot(AsmToken::Comma))
2735 return TokError("unexpected token in directive");
2736 Lex();
2737
2738 int64_t Offset = 0;
2739 if (ParseAbsoluteExpression(Offset))
2740 return true;
2741
2742 getStreamer().EmitCFIDefCfa(Register, Offset);
2743 return false;
2744}
2745
2746/// ParseDirectiveCFIDefCfaOffset
2747/// ::= .cfi_def_cfa_offset offset
2748bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2749 int64_t Offset = 0;
2750 if (ParseAbsoluteExpression(Offset))
2751 return true;
2752
2753 getStreamer().EmitCFIDefCfaOffset(Offset);
2754 return false;
2755}
2756
2757/// ParseDirectiveCFIRegister
2758/// ::= .cfi_register register, register
2759bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2760 int64_t Register1 = 0;
2761 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2762 return true;
2763
2764 if (getLexer().isNot(AsmToken::Comma))
2765 return TokError("unexpected token in directive");
2766 Lex();
2767
2768 int64_t Register2 = 0;
2769 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2770 return true;
2771
2772 getStreamer().EmitCFIRegister(Register1, Register2);
2773 return false;
2774}
2775
2776/// ParseDirectiveCFIAdjustCfaOffset
2777/// ::= .cfi_adjust_cfa_offset adjustment
2778bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2779 int64_t Adjustment = 0;
2780 if (ParseAbsoluteExpression(Adjustment))
2781 return true;
2782
2783 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2784 return false;
2785}
2786
2787/// ParseDirectiveCFIDefCfaRegister
2788/// ::= .cfi_def_cfa_register register
2789bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2790 int64_t Register = 0;
2791 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2792 return true;
2793
2794 getStreamer().EmitCFIDefCfaRegister(Register);
2795 return false;
2796}
2797
2798/// ParseDirectiveCFIOffset
2799/// ::= .cfi_offset register, offset
2800bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2801 int64_t Register = 0;
2802 int64_t Offset = 0;
2803
2804 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2805 return true;
2806
2807 if (getLexer().isNot(AsmToken::Comma))
2808 return TokError("unexpected token in directive");
2809 Lex();
2810
2811 if (ParseAbsoluteExpression(Offset))
2812 return true;
2813
2814 getStreamer().EmitCFIOffset(Register, Offset);
2815 return false;
2816}
2817
2818/// ParseDirectiveCFIRelOffset
2819/// ::= .cfi_rel_offset register, offset
2820bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2821 int64_t Register = 0;
2822
2823 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2824 return true;
2825
2826 if (getLexer().isNot(AsmToken::Comma))
2827 return TokError("unexpected token in directive");
2828 Lex();
2829
2830 int64_t Offset = 0;
2831 if (ParseAbsoluteExpression(Offset))
2832 return true;
2833
2834 getStreamer().EmitCFIRelOffset(Register, Offset);
2835 return false;
2836}
2837
2838static bool isValidEncoding(int64_t Encoding) {
2839 if (Encoding & ~0xff)
2840 return false;
2841
2842 if (Encoding == dwarf::DW_EH_PE_omit)
2843 return true;
2844
2845 const unsigned Format = Encoding & 0xf;
2846 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2847 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2848 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2849 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2850 return false;
2851
2852 const unsigned Application = Encoding & 0x70;
2853 if (Application != dwarf::DW_EH_PE_absptr &&
2854 Application != dwarf::DW_EH_PE_pcrel)
2855 return false;
2856
2857 return true;
2858}
2859
2860/// ParseDirectiveCFIPersonalityOrLsda
2861/// IsPersonality true for cfi_personality, false for cfi_lsda
2862/// ::= .cfi_personality encoding, [symbol_name]
2863/// ::= .cfi_lsda encoding, [symbol_name]
2864bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2865 int64_t Encoding = 0;
2866 if (ParseAbsoluteExpression(Encoding))
2867 return true;
2868 if (Encoding == dwarf::DW_EH_PE_omit)
2869 return false;
2870
2871 if (!isValidEncoding(Encoding))
2872 return TokError("unsupported encoding.");
2873
2874 if (getLexer().isNot(AsmToken::Comma))
2875 return TokError("unexpected token in directive");
2876 Lex();
2877
2878 StringRef Name;
2879 if (ParseIdentifier(Name))
2880 return TokError("expected identifier in directive");
2881
2882 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2883
2884 if (IsPersonality)
2885 getStreamer().EmitCFIPersonality(Sym, Encoding);
2886 else
2887 getStreamer().EmitCFILsda(Sym, Encoding);
2888 return false;
2889}
2890
2891/// ParseDirectiveCFIRememberState
2892/// ::= .cfi_remember_state
2893bool AsmParser::ParseDirectiveCFIRememberState() {
2894 getStreamer().EmitCFIRememberState();
2895 return false;
2896}
2897
2898/// ParseDirectiveCFIRestoreState
2899/// ::= .cfi_remember_state
2900bool AsmParser::ParseDirectiveCFIRestoreState() {
2901 getStreamer().EmitCFIRestoreState();
2902 return false;
2903}
2904
2905/// ParseDirectiveCFISameValue
2906/// ::= .cfi_same_value register
2907bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2908 int64_t Register = 0;
2909
2910 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2911 return true;
2912
2913 getStreamer().EmitCFISameValue(Register);
2914 return false;
2915}
2916
2917/// ParseDirectiveCFIRestore
2918/// ::= .cfi_restore register
2919bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2920 int64_t Register = 0;
2921 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2922 return true;
2923
2924 getStreamer().EmitCFIRestore(Register);
2925 return false;
2926}
2927
2928/// ParseDirectiveCFIEscape
2929/// ::= .cfi_escape expression[,...]
2930bool AsmParser::ParseDirectiveCFIEscape() {
2931 std::string Values;
2932 int64_t CurrValue;
2933 if (ParseAbsoluteExpression(CurrValue))
2934 return true;
2935
2936 Values.push_back((uint8_t)CurrValue);
2937
2938 while (getLexer().is(AsmToken::Comma)) {
2939 Lex();
2940
2941 if (ParseAbsoluteExpression(CurrValue))
2942 return true;
2943
2944 Values.push_back((uint8_t)CurrValue);
2945 }
2946
2947 getStreamer().EmitCFIEscape(Values);
2948 return false;
2949}
2950
2951/// ParseDirectiveCFISignalFrame
2952/// ::= .cfi_signal_frame
2953bool AsmParser::ParseDirectiveCFISignalFrame() {
2954 if (getLexer().isNot(AsmToken::EndOfStatement))
2955 return Error(getLexer().getLoc(),
2956 "unexpected token in '.cfi_signal_frame'");
2957
2958 getStreamer().EmitCFISignalFrame();
2959 return false;
2960}
2961
2962/// ParseDirectiveCFIUndefined
2963/// ::= .cfi_undefined register
2964bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2965 int64_t Register = 0;
2966
2967 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2968 return true;
2969
2970 getStreamer().EmitCFIUndefined(Register);
2971 return false;
2972}
2973
2974/// ParseDirectiveMacrosOnOff
2975/// ::= .macros_on
2976/// ::= .macros_off
2977bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2978 if (getLexer().isNot(AsmToken::EndOfStatement))
2979 return Error(getLexer().getLoc(),
2980 "unexpected token in '" + Directive + "' directive");
2981
2982 SetMacrosEnabled(Directive == ".macros_on");
2983 return false;
2984}
2985
2986/// ParseDirectiveMacro
2987/// ::= .macro name [parameters]
2988bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2989 StringRef Name;
2990 if (ParseIdentifier(Name))
2991 return TokError("expected identifier in '.macro' directive");
2992
2993 MCAsmMacroParameters Parameters;
2994 // Argument delimiter is initially unknown. It will be set by
2995 // ParseMacroArgument()
2996 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2997 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2998 for (;;) {
2999 MCAsmMacroParameter Parameter;
3000 if (ParseIdentifier(Parameter.first))
3001 return TokError("expected identifier in '.macro' directive");
3002
3003 if (getLexer().is(AsmToken::Equal)) {
3004 Lex();
3005 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3006 return true;
3007 }
3008
3009 Parameters.push_back(Parameter);
3010
3011 if (getLexer().is(AsmToken::Comma))
3012 Lex();
3013 else if (getLexer().is(AsmToken::EndOfStatement))
3014 break;
3015 }
3016 }
3017
3018 // Eat the end of statement.
3019 Lex();
3020
3021 AsmToken EndToken, StartToken = getTok();
3022
3023 // Lex the macro definition.
3024 for (;;) {
3025 // Check whether we have reached the end of the file.
3026 if (getLexer().is(AsmToken::Eof))
3027 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3028
3029 // Otherwise, check whether we have reach the .endmacro.
3030 if (getLexer().is(AsmToken::Identifier) &&
3031 (getTok().getIdentifier() == ".endm" ||
3032 getTok().getIdentifier() == ".endmacro")) {
3033 EndToken = getTok();
3034 Lex();
3035 if (getLexer().isNot(AsmToken::EndOfStatement))
3036 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3037 "' directive");
3038 break;
3039 }
3040
3041 // Otherwise, scan til the end of the statement.
3042 EatToEndOfStatement();
3043 }
3044
3045 if (LookupMacro(Name)) {
3046 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3047 }
3048
3049 const char *BodyStart = StartToken.getLoc().getPointer();
3050 const char *BodyEnd = EndToken.getLoc().getPointer();
3051 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003052 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003053 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3054 return false;
3055}
3056
Kevin Enderby221514e2013-01-22 21:44:53 +00003057/// CheckForBadMacro
3058///
3059/// With the support added for named parameters there may be code out there that
3060/// is transitioning from positional parameters. In versions of gas that did
3061/// not support named parameters they would be ignored on the macro defintion.
3062/// But to support both styles of parameters this is not possible so if a macro
3063/// defintion has named parameters but does not use them and has what appears
3064/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3065/// warning that the positional parameter found in body which have no effect.
3066/// Hoping the developer will either remove the named parameters from the macro
3067/// definiton so the positional parameters get used if that was what was
3068/// intended or change the macro to use the named parameters. It is possible
3069/// this warning will trigger when the none of the named parameters are used
3070/// and the strings like $1 are infact to simply to be passed trough unchanged.
3071void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3072 StringRef Body,
3073 MCAsmMacroParameters Parameters) {
3074 // If this macro is not defined with named parameters the warning we are
3075 // checking for here doesn't apply.
3076 unsigned NParameters = Parameters.size();
3077 if (NParameters == 0)
3078 return;
3079
3080 bool NamedParametersFound = false;
3081 bool PositionalParametersFound = false;
3082
3083 // Look at the body of the macro for use of both the named parameters and what
3084 // are likely to be positional parameters. This is what expandMacro() is
3085 // doing when it finds the parameters in the body.
3086 while (!Body.empty()) {
3087 // Scan for the next possible parameter.
3088 std::size_t End = Body.size(), Pos = 0;
3089 for (; Pos != End; ++Pos) {
3090 // Check for a substitution or escape.
3091 // This macro is defined with parameters, look for \foo, \bar, etc.
3092 if (Body[Pos] == '\\' && Pos + 1 != End)
3093 break;
3094
3095 // This macro should have parameters, but look for $0, $1, ..., $n too.
3096 if (Body[Pos] != '$' || Pos + 1 == End)
3097 continue;
3098 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003099 if (Next == '$' || Next == 'n' ||
3100 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003101 break;
3102 }
3103
3104 // Check if we reached the end.
3105 if (Pos == End)
3106 break;
3107
3108 if (Body[Pos] == '$') {
3109 switch (Body[Pos+1]) {
3110 // $$ => $
3111 case '$':
3112 break;
3113
3114 // $n => number of arguments
3115 case 'n':
3116 PositionalParametersFound = true;
3117 break;
3118
3119 // $[0-9] => argument
3120 default: {
3121 PositionalParametersFound = true;
3122 break;
3123 }
3124 }
3125 Pos += 2;
3126 } else {
3127 unsigned I = Pos + 1;
3128 while (isIdentifierChar(Body[I]) && I + 1 != End)
3129 ++I;
3130
3131 const char *Begin = Body.data() + Pos +1;
3132 StringRef Argument(Begin, I - (Pos +1));
3133 unsigned Index = 0;
3134 for (; Index < NParameters; ++Index)
3135 if (Parameters[Index].first == Argument)
3136 break;
3137
3138 if (Index == NParameters) {
3139 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3140 Pos += 3;
3141 else {
3142 Pos = I;
3143 }
3144 } else {
3145 NamedParametersFound = true;
3146 Pos += 1 + Argument.size();
3147 }
3148 }
3149 // Update the scan point.
3150 Body = Body.substr(Pos);
3151 }
3152
3153 if (!NamedParametersFound && PositionalParametersFound)
3154 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3155 "used in macro body, possible positional parameter "
3156 "found in body which will have no effect");
3157}
3158
Eli Bendersky6ee13082013-01-15 22:59:42 +00003159/// ParseDirectiveEndMacro
3160/// ::= .endm
3161/// ::= .endmacro
3162bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3163 if (getLexer().isNot(AsmToken::EndOfStatement))
3164 return TokError("unexpected token in '" + Directive + "' directive");
3165
3166 // If we are inside a macro instantiation, terminate the current
3167 // instantiation.
3168 if (InsideMacroInstantiation()) {
3169 HandleMacroExit();
3170 return false;
3171 }
3172
3173 // Otherwise, this .endmacro is a stray entry in the file; well formed
3174 // .endmacro directives are handled during the macro definition parsing.
3175 return TokError("unexpected '" + Directive + "' in file, "
3176 "no current macro definition");
3177}
3178
3179/// ParseDirectivePurgeMacro
3180/// ::= .purgem
3181bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3182 StringRef Name;
3183 if (ParseIdentifier(Name))
3184 return TokError("expected identifier in '.purgem' directive");
3185
3186 if (getLexer().isNot(AsmToken::EndOfStatement))
3187 return TokError("unexpected token in '.purgem' directive");
3188
3189 if (!LookupMacro(Name))
3190 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3191
3192 UndefineMacro(Name);
3193 return false;
3194}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003195
3196/// ParseDirectiveBundleAlignMode
3197/// ::= {.bundle_align_mode} expression
3198bool AsmParser::ParseDirectiveBundleAlignMode() {
3199 CheckForValidSection();
3200
3201 // Expect a single argument: an expression that evaluates to a constant
3202 // in the inclusive range 0-30.
3203 SMLoc ExprLoc = getLexer().getLoc();
3204 int64_t AlignSizePow2;
3205 if (ParseAbsoluteExpression(AlignSizePow2))
3206 return true;
3207 else if (getLexer().isNot(AsmToken::EndOfStatement))
3208 return TokError("unexpected token after expression in"
3209 " '.bundle_align_mode' directive");
3210 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3211 return Error(ExprLoc,
3212 "invalid bundle alignment size (expected between 0 and 30)");
3213
3214 Lex();
3215
3216 // Because of AlignSizePow2's verified range we can safely truncate it to
3217 // unsigned.
3218 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3219 return false;
3220}
3221
3222/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003223/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003224bool AsmParser::ParseDirectiveBundleLock() {
3225 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003226 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003227
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003228 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3229 StringRef Option;
3230 SMLoc Loc = getTok().getLoc();
3231 const char *kInvalidOptionError =
3232 "invalid option for '.bundle_lock' directive";
3233
3234 if (ParseIdentifier(Option))
3235 return Error(Loc, kInvalidOptionError);
3236
3237 if (Option != "align_to_end")
3238 return Error(Loc, kInvalidOptionError);
3239 else if (getLexer().isNot(AsmToken::EndOfStatement))
3240 return Error(Loc,
3241 "unexpected token after '.bundle_lock' directive option");
3242 AlignToEnd = true;
3243 }
3244
Eli Bendersky4766ef42012-12-20 19:05:53 +00003245 Lex();
3246
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003247 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003248 return false;
3249}
3250
3251/// ParseDirectiveBundleLock
3252/// ::= {.bundle_lock}
3253bool AsmParser::ParseDirectiveBundleUnlock() {
3254 CheckForValidSection();
3255
3256 if (getLexer().isNot(AsmToken::EndOfStatement))
3257 return TokError("unexpected token in '.bundle_unlock' directive");
3258 Lex();
3259
3260 getStreamer().EmitBundleUnlock();
3261 return false;
3262}
3263
Eli Bendersky6ee13082013-01-15 22:59:42 +00003264/// ParseDirectiveSpace
3265/// ::= (.skip | .space) expression [ , expression ]
3266bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3267 CheckForValidSection();
3268
3269 int64_t NumBytes;
3270 if (ParseAbsoluteExpression(NumBytes))
3271 return true;
3272
3273 int64_t FillExpr = 0;
3274 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3275 if (getLexer().isNot(AsmToken::Comma))
3276 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3277 Lex();
3278
3279 if (ParseAbsoluteExpression(FillExpr))
3280 return true;
3281
3282 if (getLexer().isNot(AsmToken::EndOfStatement))
3283 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3284 }
3285
3286 Lex();
3287
3288 if (NumBytes <= 0)
3289 return TokError("invalid number of bytes in '" +
3290 Twine(IDVal) + "' directive");
3291
3292 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3293 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3294
3295 return false;
3296}
3297
3298/// ParseDirectiveLEB128
3299/// ::= (.sleb128 | .uleb128) expression
3300bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3301 CheckForValidSection();
3302 const MCExpr *Value;
3303
3304 if (ParseExpression(Value))
3305 return true;
3306
3307 if (getLexer().isNot(AsmToken::EndOfStatement))
3308 return TokError("unexpected token in directive");
3309
3310 if (Signed)
3311 getStreamer().EmitSLEB128Value(Value);
3312 else
3313 getStreamer().EmitULEB128Value(Value);
3314
3315 return false;
3316}
3317
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003318/// ParseDirectiveSymbolAttribute
3319/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003320bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003321 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003322 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003323 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003324 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003325
3326 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003327 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003328
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003329 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003330
Jim Grosbach10ec6502011-09-15 17:56:49 +00003331 // Assembler local symbols don't make any sense here. Complain loudly.
3332 if (Sym->isTemporary())
3333 return Error(Loc, "non-local symbol required in directive");
3334
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003335 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003336
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003337 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003338 break;
3339
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003340 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003341 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003342 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003343 }
3344 }
3345
Sean Callanan79ed1a82010-01-19 20:22:31 +00003346 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003347 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003348}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003349
3350/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003351/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3352bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003353 CheckForValidSection();
3354
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003355 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003356 StringRef Name;
3357 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003358 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003359
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003360 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003361 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003362
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003363 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003364 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003365 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003366
3367 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003368 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003369 if (ParseAbsoluteExpression(Size))
3370 return true;
3371
3372 int64_t Pow2Alignment = 0;
3373 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003374 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003375 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003376 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003377 if (ParseAbsoluteExpression(Pow2Alignment))
3378 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003379
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003380 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3381 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003382 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3383
Chris Lattner258281d2010-01-19 06:22:22 +00003384 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003385 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3386 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003387 if (!isPowerOf2_64(Pow2Alignment))
3388 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3389 Pow2Alignment = Log2_64(Pow2Alignment);
3390 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003391 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003392
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003393 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003394 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003395
Sean Callanan79ed1a82010-01-19 20:22:31 +00003396 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003397
Chris Lattner1fc3d752009-07-09 17:25:12 +00003398 // NOTE: a size of zero for a .comm should create a undefined symbol
3399 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003400 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003401 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3402 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003403
Eric Christopherc260a3e2010-05-14 01:38:54 +00003404 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003405 // may internally end up wanting an alignment in bytes.
3406 // FIXME: Diagnose overflow.
3407 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003408 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3409 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003410
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003411 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003412 return Error(IDLoc, "invalid symbol redefinition");
3413
Chris Lattner1fc3d752009-07-09 17:25:12 +00003414 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003415 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003416 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003417 return false;
3418 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003419
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003420 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003421 return false;
3422}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003423
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003424/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003425/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003426bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003427 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003428 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003429
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003430 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003431 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003432 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003433
Sean Callanan79ed1a82010-01-19 20:22:31 +00003434 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003435
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003436 if (Str.empty())
3437 Error(Loc, ".abort detected. Assembly stopping.");
3438 else
3439 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003440 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003441
3442 return false;
3443}
Kevin Enderby71148242009-07-14 21:35:03 +00003444
Kevin Enderby1f049b22009-07-14 23:21:55 +00003445/// ParseDirectiveInclude
3446/// ::= .include "filename"
3447bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003448 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003449 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003450
Sean Callanan18b83232010-01-19 21:44:56 +00003451 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003452 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003453 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003454
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003455 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003456 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003457
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003458 // Strip the quotes.
3459 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003460
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003461 // Attempt to switch the lexer to the included file before consuming the end
3462 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003463 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003464 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003465 return true;
3466 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003467
3468 return false;
3469}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003470
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003471/// ParseDirectiveIncbin
3472/// ::= .incbin "filename"
3473bool AsmParser::ParseDirectiveIncbin() {
3474 if (getLexer().isNot(AsmToken::String))
3475 return TokError("expected string in '.incbin' directive");
3476
3477 std::string Filename = getTok().getString();
3478 SMLoc IncbinLoc = getLexer().getLoc();
3479 Lex();
3480
3481 if (getLexer().isNot(AsmToken::EndOfStatement))
3482 return TokError("unexpected token in '.incbin' directive");
3483
3484 // Strip the quotes.
3485 Filename = Filename.substr(1, Filename.size()-2);
3486
3487 // Attempt to process the included file.
3488 if (ProcessIncbinFile(Filename)) {
3489 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3490 return true;
3491 }
3492
3493 return false;
3494}
3495
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003496/// ParseDirectiveIf
3497/// ::= .if expression
3498bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003499 TheCondStack.push_back(TheCondState);
3500 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003501 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003502 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003503 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003504 int64_t ExprValue;
3505 if (ParseAbsoluteExpression(ExprValue))
3506 return true;
3507
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003508 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003509 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003510
Sean Callanan79ed1a82010-01-19 20:22:31 +00003511 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003512
3513 TheCondState.CondMet = ExprValue;
3514 TheCondState.Ignore = !TheCondState.CondMet;
3515 }
3516
3517 return false;
3518}
3519
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003520/// ParseDirectiveIfb
3521/// ::= .ifb string
3522bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3523 TheCondStack.push_back(TheCondState);
3524 TheCondState.TheCond = AsmCond::IfCond;
3525
Benjamin Kramer29739e72012-05-12 16:52:21 +00003526 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003527 EatToEndOfStatement();
3528 } else {
3529 StringRef Str = ParseStringToEndOfStatement();
3530
3531 if (getLexer().isNot(AsmToken::EndOfStatement))
3532 return TokError("unexpected token in '.ifb' directive");
3533
3534 Lex();
3535
3536 TheCondState.CondMet = ExpectBlank == Str.empty();
3537 TheCondState.Ignore = !TheCondState.CondMet;
3538 }
3539
3540 return false;
3541}
3542
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003543/// ParseDirectiveIfc
3544/// ::= .ifc string1, string2
3545bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3546 TheCondStack.push_back(TheCondState);
3547 TheCondState.TheCond = AsmCond::IfCond;
3548
Benjamin Kramer29739e72012-05-12 16:52:21 +00003549 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003550 EatToEndOfStatement();
3551 } else {
3552 StringRef Str1 = ParseStringToComma();
3553
3554 if (getLexer().isNot(AsmToken::Comma))
3555 return TokError("unexpected token in '.ifc' directive");
3556
3557 Lex();
3558
3559 StringRef Str2 = ParseStringToEndOfStatement();
3560
3561 if (getLexer().isNot(AsmToken::EndOfStatement))
3562 return TokError("unexpected token in '.ifc' directive");
3563
3564 Lex();
3565
3566 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3567 TheCondState.Ignore = !TheCondState.CondMet;
3568 }
3569
3570 return false;
3571}
3572
3573/// ParseDirectiveIfdef
3574/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003575bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3576 StringRef Name;
3577 TheCondStack.push_back(TheCondState);
3578 TheCondState.TheCond = AsmCond::IfCond;
3579
3580 if (TheCondState.Ignore) {
3581 EatToEndOfStatement();
3582 } else {
3583 if (ParseIdentifier(Name))
3584 return TokError("expected identifier after '.ifdef'");
3585
3586 Lex();
3587
3588 MCSymbol *Sym = getContext().LookupSymbol(Name);
3589
3590 if (expect_defined)
3591 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3592 else
3593 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3594 TheCondState.Ignore = !TheCondState.CondMet;
3595 }
3596
3597 return false;
3598}
3599
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003600/// ParseDirectiveElseIf
3601/// ::= .elseif expression
3602bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3603 if (TheCondState.TheCond != AsmCond::IfCond &&
3604 TheCondState.TheCond != AsmCond::ElseIfCond)
3605 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3606 " an .elseif");
3607 TheCondState.TheCond = AsmCond::ElseIfCond;
3608
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003609 bool LastIgnoreState = false;
3610 if (!TheCondStack.empty())
3611 LastIgnoreState = TheCondStack.back().Ignore;
3612 if (LastIgnoreState || TheCondState.CondMet) {
3613 TheCondState.Ignore = true;
3614 EatToEndOfStatement();
3615 }
3616 else {
3617 int64_t ExprValue;
3618 if (ParseAbsoluteExpression(ExprValue))
3619 return true;
3620
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003621 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003622 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003623
Sean Callanan79ed1a82010-01-19 20:22:31 +00003624 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003625 TheCondState.CondMet = ExprValue;
3626 TheCondState.Ignore = !TheCondState.CondMet;
3627 }
3628
3629 return false;
3630}
3631
3632/// ParseDirectiveElse
3633/// ::= .else
3634bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003635 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003636 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003637
Sean Callanan79ed1a82010-01-19 20:22:31 +00003638 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003639
3640 if (TheCondState.TheCond != AsmCond::IfCond &&
3641 TheCondState.TheCond != AsmCond::ElseIfCond)
3642 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3643 ".elseif");
3644 TheCondState.TheCond = AsmCond::ElseCond;
3645 bool LastIgnoreState = false;
3646 if (!TheCondStack.empty())
3647 LastIgnoreState = TheCondStack.back().Ignore;
3648 if (LastIgnoreState || TheCondState.CondMet)
3649 TheCondState.Ignore = true;
3650 else
3651 TheCondState.Ignore = false;
3652
3653 return false;
3654}
3655
3656/// ParseDirectiveEndIf
3657/// ::= .endif
3658bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003659 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003660 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003661
Sean Callanan79ed1a82010-01-19 20:22:31 +00003662 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003663
3664 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3665 TheCondStack.empty())
3666 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3667 ".else");
3668 if (!TheCondStack.empty()) {
3669 TheCondState = TheCondStack.back();
3670 TheCondStack.pop_back();
3671 }
3672
3673 return false;
3674}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003675
Eli Bendersky6ee13082013-01-15 22:59:42 +00003676void AsmParser::initializeDirectiveKindMap() {
3677 DirectiveKindMap[".set"] = DK_SET;
3678 DirectiveKindMap[".equ"] = DK_EQU;
3679 DirectiveKindMap[".equiv"] = DK_EQUIV;
3680 DirectiveKindMap[".ascii"] = DK_ASCII;
3681 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3682 DirectiveKindMap[".string"] = DK_STRING;
3683 DirectiveKindMap[".byte"] = DK_BYTE;
3684 DirectiveKindMap[".short"] = DK_SHORT;
3685 DirectiveKindMap[".value"] = DK_VALUE;
3686 DirectiveKindMap[".2byte"] = DK_2BYTE;
3687 DirectiveKindMap[".long"] = DK_LONG;
3688 DirectiveKindMap[".int"] = DK_INT;
3689 DirectiveKindMap[".4byte"] = DK_4BYTE;
3690 DirectiveKindMap[".quad"] = DK_QUAD;
3691 DirectiveKindMap[".8byte"] = DK_8BYTE;
3692 DirectiveKindMap[".single"] = DK_SINGLE;
3693 DirectiveKindMap[".float"] = DK_FLOAT;
3694 DirectiveKindMap[".double"] = DK_DOUBLE;
3695 DirectiveKindMap[".align"] = DK_ALIGN;
3696 DirectiveKindMap[".align32"] = DK_ALIGN32;
3697 DirectiveKindMap[".balign"] = DK_BALIGN;
3698 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3699 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3700 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3701 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3702 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3703 DirectiveKindMap[".org"] = DK_ORG;
3704 DirectiveKindMap[".fill"] = DK_FILL;
3705 DirectiveKindMap[".zero"] = DK_ZERO;
3706 DirectiveKindMap[".extern"] = DK_EXTERN;
3707 DirectiveKindMap[".globl"] = DK_GLOBL;
3708 DirectiveKindMap[".global"] = DK_GLOBAL;
3709 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3710 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3711 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3712 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3713 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3714 DirectiveKindMap[".reference"] = DK_REFERENCE;
3715 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3716 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3717 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3718 DirectiveKindMap[".comm"] = DK_COMM;
3719 DirectiveKindMap[".common"] = DK_COMMON;
3720 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3721 DirectiveKindMap[".abort"] = DK_ABORT;
3722 DirectiveKindMap[".include"] = DK_INCLUDE;
3723 DirectiveKindMap[".incbin"] = DK_INCBIN;
3724 DirectiveKindMap[".code16"] = DK_CODE16;
3725 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3726 DirectiveKindMap[".rept"] = DK_REPT;
3727 DirectiveKindMap[".irp"] = DK_IRP;
3728 DirectiveKindMap[".irpc"] = DK_IRPC;
3729 DirectiveKindMap[".endr"] = DK_ENDR;
3730 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3731 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3732 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3733 DirectiveKindMap[".if"] = DK_IF;
3734 DirectiveKindMap[".ifb"] = DK_IFB;
3735 DirectiveKindMap[".ifnb"] = DK_IFNB;
3736 DirectiveKindMap[".ifc"] = DK_IFC;
3737 DirectiveKindMap[".ifnc"] = DK_IFNC;
3738 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3739 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3740 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3741 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3742 DirectiveKindMap[".else"] = DK_ELSE;
3743 DirectiveKindMap[".endif"] = DK_ENDIF;
3744 DirectiveKindMap[".skip"] = DK_SKIP;
3745 DirectiveKindMap[".space"] = DK_SPACE;
3746 DirectiveKindMap[".file"] = DK_FILE;
3747 DirectiveKindMap[".line"] = DK_LINE;
3748 DirectiveKindMap[".loc"] = DK_LOC;
3749 DirectiveKindMap[".stabs"] = DK_STABS;
3750 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3751 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3752 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3753 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3754 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3755 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3756 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3757 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3758 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3759 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3760 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3761 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3762 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3763 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3764 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3765 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3766 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3767 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3768 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3769 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3770 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3771 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3772 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3773 DirectiveKindMap[".macro"] = DK_MACRO;
3774 DirectiveKindMap[".endm"] = DK_ENDM;
3775 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3776 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003777}
3778
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003779
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003780MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003781 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003782
Rafael Espindola761cb062012-06-03 23:57:14 +00003783 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003784 for (;;) {
3785 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003786 if (getLexer().is(AsmToken::Eof)) {
3787 Error(DirectiveLoc, "no matching '.endr' in definition");
3788 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003789 }
3790
Rafael Espindola761cb062012-06-03 23:57:14 +00003791 if (Lexer.is(AsmToken::Identifier) &&
3792 (getTok().getIdentifier() == ".rept")) {
3793 ++NestLevel;
3794 }
3795
3796 // Otherwise, check whether we have reached the .endr.
3797 if (Lexer.is(AsmToken::Identifier) &&
3798 getTok().getIdentifier() == ".endr") {
3799 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003800 EndToken = getTok();
3801 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003802 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3803 TokError("unexpected token in '.endr' directive");
3804 return 0;
3805 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003806 break;
3807 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003808 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003809 }
3810
Rafael Espindola761cb062012-06-03 23:57:14 +00003811 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003812 EatToEndOfStatement();
3813 }
3814
3815 const char *BodyStart = StartToken.getLoc().getPointer();
3816 const char *BodyEnd = EndToken.getLoc().getPointer();
3817 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3818
Rafael Espindola761cb062012-06-03 23:57:14 +00003819 // We Are Anonymous.
3820 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003821 MCAsmMacroParameters Parameters;
3822 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003823}
3824
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003825void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003826 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003827 OS << ".endr\n";
3828
3829 MemoryBuffer *Instantiation =
3830 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3831
Rafael Espindola761cb062012-06-03 23:57:14 +00003832 // Create the macro instantiation object and add to the current macro
3833 // instantiation stack.
3834 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003835 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003836 getTok().getLoc(),
3837 Instantiation);
3838 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003839
Rafael Espindola761cb062012-06-03 23:57:14 +00003840 // Jump to the macro instantiation and prime the lexer.
3841 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3842 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3843 Lex();
3844}
3845
3846bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3847 int64_t Count;
3848 if (ParseAbsoluteExpression(Count))
3849 return TokError("unexpected token in '.rept' directive");
3850
3851 if (Count < 0)
3852 return TokError("Count is negative");
3853
3854 if (Lexer.isNot(AsmToken::EndOfStatement))
3855 return TokError("unexpected token in '.rept' directive");
3856
3857 // Eat the end of statement.
3858 Lex();
3859
3860 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003861 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003862 if (!M)
3863 return true;
3864
3865 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3866 // to hold the macro body with substitutions.
3867 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003868 MCAsmMacroParameters Parameters;
3869 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003870 raw_svector_ostream OS(Buf);
3871 while (Count--) {
3872 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3873 return true;
3874 }
3875 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003876
3877 return false;
3878}
3879
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003880/// ParseDirectiveIrp
3881/// ::= .irp symbol,values
3882bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003883 MCAsmMacroParameters Parameters;
3884 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003885
Preston Gurd6c9176a2012-09-19 20:29:04 +00003886 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003887 return TokError("expected identifier in '.irp' directive");
3888
3889 Parameters.push_back(Parameter);
3890
3891 if (Lexer.isNot(AsmToken::Comma))
3892 return TokError("expected comma in '.irp' directive");
3893
3894 Lex();
3895
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003896 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003897 if (ParseMacroArguments(0, A))
3898 return true;
3899
3900 // Eat the end of statement.
3901 Lex();
3902
3903 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003904 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003905 if (!M)
3906 return true;
3907
3908 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3909 // to hold the macro body with substitutions.
3910 SmallString<256> Buf;
3911 raw_svector_ostream OS(Buf);
3912
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003913 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3914 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003915 Args.push_back(*i);
3916
3917 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3918 return true;
3919 }
3920
3921 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3922
3923 return false;
3924}
3925
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003926/// ParseDirectiveIrpc
3927/// ::= .irpc symbol,values
3928bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003929 MCAsmMacroParameters Parameters;
3930 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003931
Preston Gurd6c9176a2012-09-19 20:29:04 +00003932 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003933 return TokError("expected identifier in '.irpc' directive");
3934
3935 Parameters.push_back(Parameter);
3936
3937 if (Lexer.isNot(AsmToken::Comma))
3938 return TokError("expected comma in '.irpc' directive");
3939
3940 Lex();
3941
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003942 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003943 if (ParseMacroArguments(0, A))
3944 return true;
3945
3946 if (A.size() != 1 || A.front().size() != 1)
3947 return TokError("unexpected token in '.irpc' directive");
3948
3949 // Eat the end of statement.
3950 Lex();
3951
3952 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003953 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003954 if (!M)
3955 return true;
3956
3957 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3958 // to hold the macro body with substitutions.
3959 SmallString<256> Buf;
3960 raw_svector_ostream OS(Buf);
3961
3962 StringRef Values = A.front().front().getString();
3963 std::size_t I, End = Values.size();
3964 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003965 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003966 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3967
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003968 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003969 Args.push_back(Arg);
3970
3971 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3972 return true;
3973 }
3974
3975 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3976
3977 return false;
3978}
3979
Rafael Espindola761cb062012-06-03 23:57:14 +00003980bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3981 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003982 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003983
3984 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003985 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003986 assert(getLexer().is(AsmToken::EndOfStatement));
3987
Rafael Espindola761cb062012-06-03 23:57:14 +00003988 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003989 return false;
3990}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003991
Chad Rosiere1d64032013-02-12 19:42:32 +00003992bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info, size_t len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003993 const MCExpr *Value;
3994 SMLoc ExprLoc = getLexer().getLoc();
3995 if (ParseExpression(Value))
3996 return true;
3997 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3998 if (!MCE)
3999 return Error(ExprLoc, "unexpected expression in _emit");
4000 uint64_t IntValue = MCE->getValue();
4001 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4002 return Error(ExprLoc, "literal value out of range for directive");
4003
Chad Rosiere1d64032013-02-12 19:42:32 +00004004 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, len));
Eli Friedman2128aae2012-10-22 23:58:19 +00004005 return false;
4006}
4007
Chad Rosierb1f8c132012-10-18 15:49:34 +00004008bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4009 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004010 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00004011 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00004012 SmallVectorImpl<std::string> &Clobbers,
4013 const MCInstrInfo *MII,
4014 const MCInstPrinter *IP,
4015 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004016 SmallVector<void *, 4> InputDecls;
4017 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004018 SmallVector<bool, 4> InputDeclsAddressOf;
4019 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004020 SmallVector<std::string, 4> InputConstraints;
4021 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004022 std::set<std::string> ClobberRegs;
4023
Chad Rosier4e472d22012-10-20 01:02:45 +00004024 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004025
4026 // Prime the lexer.
4027 Lex();
4028
4029 // While we have input, parse each statement.
4030 unsigned InputIdx = 0;
4031 unsigned OutputIdx = 0;
4032 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004033 ParseStatementInfo Info(&AsmStrRewrites);
4034 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004035 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004036
Chad Rosier57498012012-12-12 22:45:52 +00004037 if (Info.ParseError)
4038 return true;
4039
Eli Friedman2128aae2012-10-22 23:58:19 +00004040 if (Info.Opcode != ~0U) {
4041 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004042
4043 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00004044 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4045 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004046
4047 // Immediate.
4048 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00004049 if (Operand->needAsmRewrite())
4050 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
4051 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004052 continue;
4053 }
4054
4055 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00004056 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004057 unsigned NumDefs = Desc.getNumDefs();
4058 // Clobber.
4059 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
4060 std::string Reg;
4061 raw_string_ostream OS(Reg);
4062 IP->printRegName(OS, Operand->getReg());
4063 ClobberRegs.insert(StringRef(OS.str()));
4064 }
4065 continue;
4066 }
4067
4068 // Expr/Input or Output.
Chad Rosierc1ec2072013-01-10 22:10:27 +00004069 bool IsVarDecl;
Chad Rosier505bca32013-01-17 19:21:48 +00004070 unsigned Length, Size, Type;
Chad Rosier32989592012-10-18 20:27:15 +00004071 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosier505bca32013-01-17 19:21:48 +00004072 Length, Size, Type, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004073 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004074 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00004075 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00004076 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00004077 Operand->getStartLoc(),
4078 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004079 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004080 if (isOutput) {
4081 std::string Constraint = "=";
4082 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004083 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00004084 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00004085 Constraint += Operand->getConstraint().str();
4086 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00004087 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004088 Operand->getStartLoc(),
4089 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004090 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004091 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00004092 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00004093 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00004094 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004095 Operand->getStartLoc(),
4096 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004097 }
4098 }
4099 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004100 }
4101 }
4102
4103 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004104 NumOutputs = OutputDecls.size();
4105 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004106
4107 // Set the unique clobbers.
4108 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4109 E = ClobberRegs.end(); I != E; ++I)
4110 Clobbers.push_back(*I);
4111
4112 // Merge the various outputs and inputs. Output are expected first.
4113 if (NumOutputs || NumInputs) {
4114 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004115 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004116 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004117 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004118 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004119 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004120 }
4121 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004122 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004123 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004124 }
4125 }
4126
4127 // Build the IR assembly string.
4128 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004129 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004130 raw_string_ostream OS(AsmStringIR);
4131 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00004132 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004133 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4134 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004135
Chad Rosier4e472d22012-10-20 01:02:45 +00004136 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004137
4138 // Emit everything up to the immediate/expression. If the previous rewrite
4139 // was a size directive, then this has already been done.
4140 if (PrevKind != AOK_SizeDirective)
4141 OS << StringRef(Start, Loc - Start);
4142 PrevKind = Kind;
4143
Chad Rosier5a719fc2012-10-23 17:43:43 +00004144 // Skip the original expression.
4145 if (Kind == AOK_Skip) {
4146 Start = Loc + (*I).Len;
4147 continue;
4148 }
4149
Chad Rosierb1f8c132012-10-18 15:49:34 +00004150 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004151 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004152 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004153 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004154 OS << Twine("$$");
4155 OS << (*I).Val;
4156 break;
4157 case AOK_ImmPrefix:
4158 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004159 break;
4160 case AOK_Input:
4161 OS << '$';
4162 OS << InputIdx++;
4163 break;
4164 case AOK_Output:
4165 OS << '$';
4166 OS << OutputIdx++;
4167 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004168 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004169 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004170 default: break;
4171 case 8: OS << "byte ptr "; break;
4172 case 16: OS << "word ptr "; break;
4173 case 32: OS << "dword ptr "; break;
4174 case 64: OS << "qword ptr "; break;
4175 case 80: OS << "xword ptr "; break;
4176 case 128: OS << "xmmword ptr "; break;
4177 case 256: OS << "ymmword ptr "; break;
4178 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004179 break;
4180 case AOK_Emit:
4181 OS << ".byte";
4182 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004183 case AOK_DotOperator:
4184 OS << (*I).Val;
4185 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004186 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004187
Chad Rosierb1f8c132012-10-18 15:49:34 +00004188 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004189 if (Kind != AOK_SizeDirective)
4190 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004191 }
4192
4193 // Emit the remainder of the asm string.
4194 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4195 if (Start != AsmEnd)
4196 OS << StringRef(Start, AsmEnd - Start);
4197
4198 AsmString = OS.str();
4199 return false;
4200}
4201
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004202/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004203MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004204 MCContext &C, MCStreamer &Out,
4205 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004206 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004207}