blob: 4d6756e1b62ff01ccf576ecfe1e34a21333ae190 [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"
447 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000448
Eli Bendersky6ee13082013-01-15 22:59:42 +0000449 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000450};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000451}
452
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000453namespace llvm {
454
455extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000456extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000457extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000458
459}
460
Chris Lattneraaec2052010-01-19 19:46:13 +0000461enum { DEFAULT_ADDRSPACE = 0 };
462
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000463AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000464 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000465 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000466 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000467 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000468 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000469 // Save the old handler.
470 SavedDiagHandler = SrcMgr.getDiagHandler();
471 SavedDiagContext = SrcMgr.getDiagContext();
472 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000473 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000474 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000475
Daniel Dunbare4749702010-07-12 18:12:02 +0000476 // Initialize the platform / file format parser.
477 //
478 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
479 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000480 if (_MAI.hasMicrosoftFastStdCallMangling()) {
481 PlatformParser = createCOFFAsmParser();
482 PlatformParser->Initialize(*this);
483 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000484 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000485 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000486 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000487 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000488 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000489 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000490 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000491
Eli Bendersky6ee13082013-01-15 22:59:42 +0000492 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000493}
494
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000495AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000496 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
497
498 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000499 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000500 ie = MacroMap.end(); it != ie; ++it)
501 delete it->getValue();
502
Daniel Dunbare4749702010-07-12 18:12:02 +0000503 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000504}
505
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000506void AsmParser::PrintMacroInstantiations() {
507 // Print the active macro instantiation stack.
508 for (std::vector<MacroInstantiation*>::const_reverse_iterator
509 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000510 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
511 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000512}
513
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000514bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000515 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000516 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000517 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000518 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000519 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000520}
521
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000522bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000523 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000524 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000525 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000526 return true;
527}
528
Sean Callananfd0b0282010-01-21 00:19:58 +0000529bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000530 std::string IncludedFile;
531 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000532 if (NewBuf == -1)
533 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000536
Sean Callananfd0b0282010-01-21 00:19:58 +0000537 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000538
Sean Callananfd0b0282010-01-21 00:19:58 +0000539 return false;
540}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000541
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000542/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000543/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000544/// returns true on failure.
545bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
546 std::string IncludedFile;
547 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
548 if (NewBuf == -1)
549 return true;
550
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000551 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000552 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
553 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000554 return false;
555}
556
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000557void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
558 if (InBuffer != -1) {
559 CurBuffer = InBuffer;
560 } else {
561 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
562 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000563 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
564}
565
Sean Callananfd0b0282010-01-21 00:19:58 +0000566const AsmToken &AsmParser::Lex() {
567 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000568
Sean Callananfd0b0282010-01-21 00:19:58 +0000569 if (tok->is(AsmToken::Eof)) {
570 // If this is the end of an included file, pop the parent file off the
571 // include stack.
572 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
573 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000574 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000575 tok = &Lexer.Lex();
576 }
577 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000578
Sean Callananfd0b0282010-01-21 00:19:58 +0000579 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000580 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000581
Sean Callananfd0b0282010-01-21 00:19:58 +0000582 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000583}
584
Chris Lattner79180e22010-04-05 23:15:42 +0000585bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000586 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000587 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000588 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000589
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000590 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000591 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000592
593 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000594 AsmCond StartingCondState = TheCondState;
595
Kevin Enderby613b7572011-11-01 22:27:22 +0000596 // If we are generating dwarf for assembly source files save the initial text
597 // section and generate a .file directive.
598 if (getContext().getGenDwarfForAssembly()) {
599 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000600 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
601 getStreamer().EmitLabel(SectionStartSym);
602 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000603 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000604 StringRef(),
605 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000606 }
607
Chris Lattnerb717fb02009-07-02 21:53:43 +0000608 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000609 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000610 ParseStatementInfo Info;
611 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000612
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000613 // We had an error, validate that one was emitted and recover by skipping to
614 // the next line.
615 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000616 EatToEndOfStatement();
617 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000618
619 if (TheCondState.TheCond != StartingCondState.TheCond ||
620 TheCondState.Ignore != StartingCondState.Ignore)
621 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000622
623 // Check to see there are no empty DwarfFile slots.
624 const std::vector<MCDwarfFile *> &MCDwarfFiles =
625 getContext().getMCDwarfFiles();
626 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000627 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000628 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000629 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000630
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000631 // Check to see that all assembler local symbols were actually defined.
632 // Targets that don't do subsections via symbols may not want this, though,
633 // so conservatively exclude them. Only do this if we're finalizing, though,
634 // as otherwise we won't necessarilly have seen everything yet.
635 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
636 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
637 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
638 e = Symbols.end();
639 i != e; ++i) {
640 MCSymbol *Sym = i->getValue();
641 // Variable symbols may not be marked as defined, so check those
642 // explicitly. If we know it's a variable, we have a definition for
643 // the purposes of this check.
644 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
645 // FIXME: We would really like to refer back to where the symbol was
646 // first referenced for a source location. We need to add something
647 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000648 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
649 "assembler local symbol '" + Sym->getName() +
650 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000651 }
652 }
653
654
Chris Lattner79180e22010-04-05 23:15:42 +0000655 // Finalize the output stream if there are no errors and if the client wants
656 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000657 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000658 Out.Finish();
659
Chris Lattnerb717fb02009-07-02 21:53:43 +0000660 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000661}
662
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000663void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000664 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000665 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000666 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000667 }
668}
669
Chris Lattner2cf5f142009-06-22 01:29:09 +0000670/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
671void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000672 while (Lexer.isNot(AsmToken::EndOfStatement) &&
673 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000674 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000675
Chris Lattner2cf5f142009-06-22 01:29:09 +0000676 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000677 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000678 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000679}
680
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000681StringRef AsmParser::ParseStringToEndOfStatement() {
682 const char *Start = getTok().getLoc().getPointer();
683
684 while (Lexer.isNot(AsmToken::EndOfStatement) &&
685 Lexer.isNot(AsmToken::Eof))
686 Lex();
687
688 const char *End = getTok().getLoc().getPointer();
689 return StringRef(Start, End - Start);
690}
Chris Lattnerc4193832009-06-22 05:51:26 +0000691
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000692StringRef AsmParser::ParseStringToComma() {
693 const char *Start = getTok().getLoc().getPointer();
694
695 while (Lexer.isNot(AsmToken::EndOfStatement) &&
696 Lexer.isNot(AsmToken::Comma) &&
697 Lexer.isNot(AsmToken::Eof))
698 Lex();
699
700 const char *End = getTok().getLoc().getPointer();
701 return StringRef(Start, End - Start);
702}
703
Chris Lattner74ec1a32009-06-22 06:32:03 +0000704/// ParseParenExpr - Parse a paren expression and return it.
705/// NOTE: This assumes the leading '(' has already been consumed.
706///
707/// parenexpr ::= expr)
708///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000709bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000711 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000712 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000713 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000714 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000715 return false;
716}
Chris Lattnerc4193832009-06-22 05:51:26 +0000717
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000718/// ParseBracketExpr - Parse a bracket expression and return it.
719/// NOTE: This assumes the leading '[' has already been consumed.
720///
721/// bracketexpr ::= expr]
722///
723bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
724 if (ParseExpression(Res)) return true;
725 if (Lexer.isNot(AsmToken::RBrac))
726 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000727 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000728 Lex();
729 return false;
730}
731
Chris Lattner74ec1a32009-06-22 06:32:03 +0000732/// ParsePrimaryExpr - Parse a primary expression and return it.
733/// primaryexpr ::= (parenexpr
734/// primaryexpr ::= symbol
735/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000736/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000738bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000739 SMLoc FirstTokenLoc = getLexer().getLoc();
740 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
741 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000742 default:
743 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000744 // If we have an error assume that we've already handled it.
745 case AsmToken::Error:
746 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000747 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000748 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000749 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000750 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000751 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000752 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000753 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000754 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000755 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000756 StringRef Identifier;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000757 if (ParseIdentifier(Identifier)) {
758 if (FirstTokenKind == AsmToken::Dollar)
759 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000760 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000761 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000762
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000763 EndLoc = SMLoc::getFromPointer(Identifier.end());
764
Daniel Dunbarfffff912009-10-16 01:34:54 +0000765 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000766 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000767 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000768
769 // Lookup the symbol variant if used.
770 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000771 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000772 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000773 if (Variant == MCSymbolRefExpr::VK_Invalid) {
774 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000775 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000776 }
777 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778
Daniel Dunbarfffff912009-10-16 01:34:54 +0000779 // If this is an absolute variable reference, substitute it now to preserve
780 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000781 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000782 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000783 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000784
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000785 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000786 return false;
787 }
788
789 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000790 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000791 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000792 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000793 case AsmToken::Integer: {
794 SMLoc Loc = getTok().getLoc();
795 int64_t IntVal = getTok().getIntVal();
796 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000797 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000798 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000799 // Look for 'b' or 'f' following an Integer as a directional label
800 if (Lexer.getKind() == AsmToken::Identifier) {
801 StringRef IDVal = getTok().getString();
802 if (IDVal == "f" || IDVal == "b"){
803 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
804 IDVal == "f" ? 1 : 0);
805 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
806 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000807 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000808 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000809 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000810 Lex(); // Eat identifier.
811 }
812 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000813 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000814 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000815 case AsmToken::Real: {
816 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000817 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000818 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000819 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000820 Lex(); // Eat token.
821 return false;
822 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000823 case AsmToken::Dot: {
824 // This is a '.' reference, which references the current PC. Emit a
825 // temporary label to the streamer and refer to it.
826 MCSymbol *Sym = Ctx.CreateTempSymbol();
827 Out.EmitLabel(Sym);
828 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000829 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000830 Lex(); // Eat identifier.
831 return false;
832 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000833 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000834 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000835 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000836 case AsmToken::LBrac:
837 if (!PlatformParser->HasBracketExpressions())
838 return TokError("brackets expression not supported on this target");
839 Lex(); // Eat the '['.
840 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000841 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000842 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000843 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000844 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000845 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000846 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000847 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000848 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000849 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000851 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000853 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000854 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000855 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000857 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000858 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000859 }
860}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000861
Chris Lattnerb4307b32010-01-15 19:28:38 +0000862bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000863 SMLoc EndLoc;
864 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000865}
866
Daniel Dunbarcceba832010-09-17 02:47:07 +0000867const MCExpr *
868AsmParser::ApplyModifierToExpr(const MCExpr *E,
869 MCSymbolRefExpr::VariantKind Variant) {
870 // Recurse over the given expression, rebuilding it to apply the given variant
871 // if there is exactly one symbol.
872 switch (E->getKind()) {
873 case MCExpr::Target:
874 case MCExpr::Constant:
875 return 0;
876
877 case MCExpr::SymbolRef: {
878 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
879
880 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
881 TokError("invalid variant on expression '" +
882 getTok().getIdentifier() + "' (already modified)");
883 return E;
884 }
885
886 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
887 }
888
889 case MCExpr::Unary: {
890 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
891 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
892 if (!Sub)
893 return 0;
894 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
895 }
896
897 case MCExpr::Binary: {
898 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
899 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
900 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
901
902 if (!LHS && !RHS)
903 return 0;
904
905 if (!LHS) LHS = BE->getLHS();
906 if (!RHS) RHS = BE->getRHS();
907
908 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
909 }
910 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000911
Craig Topper85814382012-02-07 05:05:23 +0000912 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000913}
914
Chris Lattner74ec1a32009-06-22 06:32:03 +0000915/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000916///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000917/// expr ::= expr &&,|| expr -> lowest.
918/// expr ::= expr |,^,&,! expr
919/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
920/// expr ::= expr <<,>> expr
921/// expr ::= expr +,- expr
922/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000923/// expr ::= primaryexpr
924///
Chris Lattner54482b42010-01-15 19:39:23 +0000925bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000926 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000927 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000928 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
929 return true;
930
Daniel Dunbarcceba832010-09-17 02:47:07 +0000931 // As a special case, we support 'a op b @ modifier' by rewriting the
932 // expression to include the modifier. This is inefficient, but in general we
933 // expect users to use 'a@modifier op b'.
934 if (Lexer.getKind() == AsmToken::At) {
935 Lex();
936
937 if (Lexer.isNot(AsmToken::Identifier))
938 return TokError("unexpected symbol modifier following '@'");
939
940 MCSymbolRefExpr::VariantKind Variant =
941 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
942 if (Variant == MCSymbolRefExpr::VK_Invalid)
943 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
944
945 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
946 if (!ModifiedRes) {
947 return TokError("invalid modifier '" + getTok().getIdentifier() +
948 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000949 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000950
Daniel Dunbarcceba832010-09-17 02:47:07 +0000951 Res = ModifiedRes;
952 Lex();
953 }
954
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000955 // Try to constant fold it up front, if possible.
956 int64_t Value;
957 if (Res->EvaluateAsAbsolute(Value))
958 Res = MCConstantExpr::Create(Value, getContext());
959
960 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000961}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000962
Chris Lattnerb4307b32010-01-15 19:28:38 +0000963bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000964 Res = 0;
965 return ParseParenExpr(Res, EndLoc) ||
966 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000967}
968
Daniel Dunbar475839e2009-06-29 20:37:27 +0000969bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000970 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000971
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000972 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000973 if (ParseExpression(Expr))
974 return true;
975
Daniel Dunbare00b0112009-10-16 01:57:52 +0000976 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000977 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000978
979 return false;
980}
981
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000982static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000983 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000984 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000985 default:
986 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000987
Jim Grosbachfbe16812011-08-20 16:24:13 +0000988 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000989 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000990 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000991 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000992 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000993 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994 return 1;
995
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000996
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000997 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000998 //
999 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001000 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001001 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001002 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001003 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001004 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001005 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001006 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001007 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001008 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001009
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001010 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001011 case AsmToken::EqualEqual:
1012 Kind = MCBinaryExpr::EQ;
1013 return 3;
1014 case AsmToken::ExclaimEqual:
1015 case AsmToken::LessGreater:
1016 Kind = MCBinaryExpr::NE;
1017 return 3;
1018 case AsmToken::Less:
1019 Kind = MCBinaryExpr::LT;
1020 return 3;
1021 case AsmToken::LessEqual:
1022 Kind = MCBinaryExpr::LTE;
1023 return 3;
1024 case AsmToken::Greater:
1025 Kind = MCBinaryExpr::GT;
1026 return 3;
1027 case AsmToken::GreaterEqual:
1028 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001029 return 3;
1030
Jim Grosbachfbe16812011-08-20 16:24:13 +00001031 // Intermediate Precedence: <<, >>
1032 case AsmToken::LessLess:
1033 Kind = MCBinaryExpr::Shl;
1034 return 4;
1035 case AsmToken::GreaterGreater:
1036 Kind = MCBinaryExpr::Shr;
1037 return 4;
1038
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001039 // High Intermediate Precedence: +, -
1040 case AsmToken::Plus:
1041 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001042 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001043 case AsmToken::Minus:
1044 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001045 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001046
Jim Grosbachfbe16812011-08-20 16:24:13 +00001047 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001048 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001049 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001050 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001051 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001052 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001053 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001054 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001055 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001056 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001057 }
1058}
1059
1060
1061/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1062/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001063bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1064 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001065 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001066 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001067 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001068
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001069 // If the next token is lower precedence than we are allowed to eat, return
1070 // successfully with what we ate already.
1071 if (TokPrec < Precedence)
1072 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001073
Sean Callanan79ed1a82010-01-19 20:22:31 +00001074 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001075
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001076 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001077 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001078 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001079
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001080 // If BinOp binds less tightly with RHS than the operator after RHS, let
1081 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001082 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001083 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001085 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 }
1087
Daniel Dunbar475839e2009-06-29 20:37:27 +00001088 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001089 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001090 }
1091}
1092
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001093/// ParseStatement:
1094/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001095/// ::= Label* Directive ...Operands... EndOfStatement
1096/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001097bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001098 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001099 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001100 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001101 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001102 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001103
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001104 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001105 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001106 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001107 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001108 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001109 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001110 if (Lexer.is(AsmToken::Hash))
1111 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001112
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001113 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001114 if (Lexer.is(AsmToken::Integer)) {
1115 LocalLabelVal = getTok().getIntVal();
1116 if (LocalLabelVal < 0) {
1117 if (!TheCondState.Ignore)
1118 return TokError("unexpected token at start of statement");
1119 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001120 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001121 IDVal = getTok().getString();
1122 Lex(); // Consume the integer token to be used as an identifier token.
1123 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001124 if (!TheCondState.Ignore)
1125 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001126 }
1127 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001128 } else if (Lexer.is(AsmToken::Dot)) {
1129 // Treat '.' as a valid identifier in this context.
1130 Lex();
1131 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001132 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001133 if (!TheCondState.Ignore)
1134 return TokError("unexpected token at start of statement");
1135 IDVal = "";
1136 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001137
Chris Lattner7834fac2010-04-17 18:14:27 +00001138 // Handle conditional assembly here before checking for skipping. We
1139 // have to do this so that .endif isn't skipped in a ".if 0" block for
1140 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001141 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001142 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001143 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001144 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1145 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001146 switch (DirKind) {
1147 default:
1148 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001149 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001150 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001151 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001152 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001153 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001154 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001155 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001157 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001158 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001159 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001160 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001161 case DK_IFNDEF:
1162 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001163 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001164 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001165 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001166 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001167 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001168 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001169 return ParseDirectiveEndIf(IDLoc);
1170 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001171
Eli Benderskyed5df012013-01-16 19:32:36 +00001172 // Ignore the statement if in the middle of inactive conditional
1173 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001174 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001175 EatToEndOfStatement();
1176 return false;
1177 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001178
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001179 // FIXME: Recurse on local labels?
1180
1181 // See what kind of statement we have.
1182 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001183 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001184 CheckForValidSection();
1185
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001186 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001187 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001188
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001189 // Diagnose attempt to use '.' as a label.
1190 if (IDVal == ".")
1191 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1192
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001193 // Diagnose attempt to use a variable as a label.
1194 //
1195 // FIXME: Diagnostics. Note the location of the definition as a label.
1196 // FIXME: This doesn't diagnose assignment to a symbol which has been
1197 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001198 MCSymbol *Sym;
1199 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001200 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001201 else
1202 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001203 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001204 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001205
Daniel Dunbar959fd882009-08-26 22:13:22 +00001206 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001207 if (!ParsingInlineAsm)
1208 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001209
Kevin Enderby94c2e852011-12-09 18:09:40 +00001210 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001211 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001212 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001213 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1214 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001215
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001216 // Consume any end of statement token, if present, to avoid spurious
1217 // AddBlankLine calls().
1218 if (Lexer.is(AsmToken::EndOfStatement)) {
1219 Lex();
1220 if (Lexer.is(AsmToken::Eof))
1221 return false;
1222 }
1223
Eli Friedman2128aae2012-10-22 23:58:19 +00001224 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001225 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001226
Daniel Dunbar3f872332009-07-28 16:08:33 +00001227 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001229 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001230
Nico Weber4c4c7322011-01-28 03:04:41 +00001231 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001232
1233 default: // Normal instruction or directive.
1234 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001235 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001236
1237 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001238 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001239 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1240 return HandleMacroEntry(M, IDLoc);
1241 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001242
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001243 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001244
1245 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001246 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001247 // There are several entities interested in parsing directives:
1248 //
1249 // 1. The target-specific assembly parser. Some directives are target
1250 // specific or may potentially behave differently on certain targets.
1251 // 2. Asm parser extensions. For example, platform-specific parsers
1252 // (like the ELF parser) register themselves as extensions.
1253 // 3. The generic directive parser implemented by this class. These are
1254 // all the directives that behave in a target and platform independent
1255 // manner, or at least have a default behavior that's shared between
1256 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001257
Eli Bendersky6ee13082013-01-15 22:59:42 +00001258 // First query the target-specific parser. It will return 'true' if it
1259 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001260 if (!getTargetParser().ParseDirective(ID))
1261 return false;
1262
Eli Bendersky6ee13082013-01-15 22:59:42 +00001263 // Next, check the extention directive map to see if any extension has
1264 // registered itself to parse this directive.
1265 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1266 ExtensionDirectiveMap.lookup(IDVal);
1267 if (Handler.first)
1268 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1269
1270 // Finally, if no one else is interested in this directive, it must be
1271 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001272 switch (DirKind) {
1273 default:
1274 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001275 case DK_SET:
1276 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001278 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001279 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001281 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001282 case DK_ASCIZ:
1283 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001284 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001286 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001287 case DK_SHORT:
1288 case DK_VALUE:
1289 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001290 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001291 case DK_LONG:
1292 case DK_INT:
1293 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001294 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001295 case DK_QUAD:
1296 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001297 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001298 case DK_SINGLE:
1299 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001302 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001303 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1305 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1306 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001308 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1309 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1310 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001319 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001329 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 EatToEndOfStatement(); // .extern is the default, ignore it.
1331 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001332 case DK_GLOBL:
1333 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001352 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001353 case DK_COMM:
1354 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001363 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001364 case DK_CODE16:
1365 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001374 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001375 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001379 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001380 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001381 case DK_SLEB128:
1382 return ParseDirectiveLEB128(true);
1383 case DK_ULEB128:
1384 return ParseDirectiveLEB128(false);
1385 case DK_SPACE:
1386 case DK_SKIP:
1387 return ParseDirectiveSpace(IDVal);
1388 case DK_FILE:
1389 return ParseDirectiveFile(IDLoc);
1390 case DK_LINE:
1391 return ParseDirectiveLine();
1392 case DK_LOC:
1393 return ParseDirectiveLoc();
1394 case DK_STABS:
1395 return ParseDirectiveStabs();
1396 case DK_CFI_SECTIONS:
1397 return ParseDirectiveCFISections();
1398 case DK_CFI_STARTPROC:
1399 return ParseDirectiveCFIStartProc();
1400 case DK_CFI_ENDPROC:
1401 return ParseDirectiveCFIEndProc();
1402 case DK_CFI_DEF_CFA:
1403 return ParseDirectiveCFIDefCfa(IDLoc);
1404 case DK_CFI_DEF_CFA_OFFSET:
1405 return ParseDirectiveCFIDefCfaOffset();
1406 case DK_CFI_ADJUST_CFA_OFFSET:
1407 return ParseDirectiveCFIAdjustCfaOffset();
1408 case DK_CFI_DEF_CFA_REGISTER:
1409 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1410 case DK_CFI_OFFSET:
1411 return ParseDirectiveCFIOffset(IDLoc);
1412 case DK_CFI_REL_OFFSET:
1413 return ParseDirectiveCFIRelOffset(IDLoc);
1414 case DK_CFI_PERSONALITY:
1415 return ParseDirectiveCFIPersonalityOrLsda(true);
1416 case DK_CFI_LSDA:
1417 return ParseDirectiveCFIPersonalityOrLsda(false);
1418 case DK_CFI_REMEMBER_STATE:
1419 return ParseDirectiveCFIRememberState();
1420 case DK_CFI_RESTORE_STATE:
1421 return ParseDirectiveCFIRestoreState();
1422 case DK_CFI_SAME_VALUE:
1423 return ParseDirectiveCFISameValue(IDLoc);
1424 case DK_CFI_RESTORE:
1425 return ParseDirectiveCFIRestore(IDLoc);
1426 case DK_CFI_ESCAPE:
1427 return ParseDirectiveCFIEscape();
1428 case DK_CFI_SIGNAL_FRAME:
1429 return ParseDirectiveCFISignalFrame();
1430 case DK_CFI_UNDEFINED:
1431 return ParseDirectiveCFIUndefined(IDLoc);
1432 case DK_CFI_REGISTER:
1433 return ParseDirectiveCFIRegister(IDLoc);
1434 case DK_MACROS_ON:
1435 case DK_MACROS_OFF:
1436 return ParseDirectiveMacrosOnOff(IDVal);
1437 case DK_MACRO:
1438 return ParseDirectiveMacro(IDLoc);
1439 case DK_ENDM:
1440 case DK_ENDMACRO:
1441 return ParseDirectiveEndMacro(IDVal);
1442 case DK_PURGEM:
1443 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001444 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001445
Jim Grosbach686c0182012-05-01 18:38:27 +00001446 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001447 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001448
Eli Friedman2128aae2012-10-22 23:58:19 +00001449 // _emit
1450 if (ParsingInlineAsm && IDVal == "_emit")
1451 return ParseDirectiveEmit(IDLoc, Info);
1452
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001453 CheckForValidSection();
1454
Chris Lattnera7f13542010-05-19 23:34:33 +00001455 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001456 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001457 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001458 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1459 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001460 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001461
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001462 // Dump the parsed representation, if requested.
1463 if (getShowParsedOperands()) {
1464 SmallString<256> Str;
1465 raw_svector_ostream OS(Str);
1466 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001467 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001468 if (i != 0)
1469 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001470 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001471 }
1472 OS << "]";
1473
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001474 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001475 }
1476
Kevin Enderby613b7572011-11-01 22:27:22 +00001477 // If we are generating dwarf for assembly source files and the current
1478 // section is the initial text section then generate a .loc directive for
1479 // the instruction.
1480 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001481 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001482
Eli Benderskyed5df012013-01-16 19:32:36 +00001483 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001484
Eli Benderskyed5df012013-01-16 19:32:36 +00001485 // If we previously parsed a cpp hash file line comment then make sure the
1486 // current Dwarf File is for the CppHashFilename if not then emit the
1487 // Dwarf File table for it and adjust the line number for the .loc.
1488 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1489 getContext().getMCDwarfFiles();
1490 if (CppHashFilename.size() != 0) {
1491 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001492 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001493 getStreamer().EmitDwarfFileDirective(
1494 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001495
Kevin Enderby32c1a822012-11-05 21:55:41 +00001496 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001497 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001498 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001499
Kevin Enderby613b7572011-11-01 22:27:22 +00001500 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001501 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001502 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001503 StringRef());
1504 }
1505
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001506 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001507 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001508 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001509 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1510 Info.ParsedOperands,
1511 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001512 ParsingInlineAsm);
1513 }
Chris Lattner98986712010-01-14 22:21:20 +00001514
Chris Lattnercbf8a982010-09-11 16:18:25 +00001515 // Don't skip the rest of the line, the instruction parser is responsible for
1516 // that.
1517 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001518}
Chris Lattner9a023f72009-06-24 04:43:34 +00001519
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001520/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1521/// since they may not be able to be tokenized to get to the end of line token.
1522void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001523 if (!Lexer.is(AsmToken::EndOfStatement))
1524 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001525 // Eat EOL.
1526 Lex();
1527}
1528
1529/// ParseCppHashLineFilenameComment as this:
1530/// ::= # number "filename"
1531/// or just as a full line comment if it doesn't have a number and a string.
1532bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1533 Lex(); // Eat the hash token.
1534
1535 if (getLexer().isNot(AsmToken::Integer)) {
1536 // Consume the line since in cases it is not a well-formed line directive,
1537 // as if were simply a full line comment.
1538 EatToEndOfLine();
1539 return false;
1540 }
1541
1542 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001543 Lex();
1544
1545 if (getLexer().isNot(AsmToken::String)) {
1546 EatToEndOfLine();
1547 return false;
1548 }
1549
1550 StringRef Filename = getTok().getString();
1551 // Get rid of the enclosing quotes.
1552 Filename = Filename.substr(1, Filename.size()-2);
1553
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001554 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1555 CppHashLoc = L;
1556 CppHashFilename = Filename;
1557 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001558 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001559
1560 // Ignore any trailing characters, they're just comment.
1561 EatToEndOfLine();
1562 return false;
1563}
1564
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001565/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001566/// for the Filename and LineNo if any in the diagnostic.
1567void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1568 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1569 raw_ostream &OS = errs();
1570
1571 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1572 const SMLoc &DiagLoc = Diag.getLoc();
1573 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1574 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1575
1576 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1577 // before printing the message.
1578 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001579 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001580 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1581 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1582 }
1583
Eric Christopher2318ba12012-12-18 00:30:54 +00001584 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001585 // manager changed or buffer changed (like in a nested include) then just
1586 // print the normal diagnostic using its Filename and LineNo.
1587 if (!Parser->CppHashLineNumber ||
1588 &DiagSrcMgr != &Parser->SrcMgr ||
1589 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001590 if (Parser->SavedDiagHandler)
1591 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1592 else
1593 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001594 return;
1595 }
1596
Eric Christopher2318ba12012-12-18 00:30:54 +00001597 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001598 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1599 // the diagnostic.
1600 const std::string Filename = Parser->CppHashFilename;
1601
1602 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1603 int CppHashLocLineNo =
1604 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1605 int LineNo = Parser->CppHashLineNumber - 1 +
1606 (DiagLocLineNo - CppHashLocLineNo);
1607
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001608 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1609 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001610 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001611 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001612
Benjamin Kramer04a04262011-10-16 10:48:29 +00001613 if (Parser->SavedDiagHandler)
1614 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1615 else
1616 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001617}
1618
Rafael Espindola799aacf2012-08-21 18:29:30 +00001619// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1620// difference being that that function accepts '@' as part of identifiers and
1621// we can't do that. AsmLexer.cpp should probably be changed to handle
1622// '@' as a special case when needed.
1623static bool isIdentifierChar(char c) {
1624 return isalnum(c) || c == '_' || c == '$' || c == '.';
1625}
1626
Rafael Espindola761cb062012-06-03 23:57:14 +00001627bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001628 const MCAsmMacroParameters &Parameters,
1629 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001630 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001631 unsigned NParameters = Parameters.size();
1632 if (NParameters != 0 && NParameters != A.size())
1633 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001634
Preston Gurd7b6f2032012-09-19 20:36:12 +00001635 // A macro without parameters is handled differently on Darwin:
1636 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001637 while (!Body.empty()) {
1638 // Scan for the next substitution.
1639 std::size_t End = Body.size(), Pos = 0;
1640 for (; Pos != End; ++Pos) {
1641 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001642 if (!NParameters) {
1643 // This macro has no parameters, look for $0, $1, etc.
1644 if (Body[Pos] != '$' || Pos + 1 == End)
1645 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001646
Rafael Espindola65366442011-06-05 02:43:45 +00001647 char Next = Body[Pos + 1];
1648 if (Next == '$' || Next == 'n' || isdigit(Next))
1649 break;
1650 } else {
1651 // This macro has parameters, look for \foo, \bar, etc.
1652 if (Body[Pos] == '\\' && Pos + 1 != End)
1653 break;
1654 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001655 }
1656
1657 // Add the prefix.
1658 OS << Body.slice(0, Pos);
1659
1660 // Check if we reached the end.
1661 if (Pos == End)
1662 break;
1663
Rafael Espindola65366442011-06-05 02:43:45 +00001664 if (!NParameters) {
1665 switch (Body[Pos+1]) {
1666 // $$ => $
1667 case '$':
1668 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001669 break;
1670
Rafael Espindola65366442011-06-05 02:43:45 +00001671 // $n => number of arguments
1672 case 'n':
1673 OS << A.size();
1674 break;
1675
1676 // $[0-9] => argument
1677 default: {
1678 // Missing arguments are ignored.
1679 unsigned Index = Body[Pos+1] - '0';
1680 if (Index >= A.size())
1681 break;
1682
1683 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001684 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001685 ie = A[Index].end(); it != ie; ++it)
1686 OS << it->getString();
1687 break;
1688 }
1689 }
1690 Pos += 2;
1691 } else {
1692 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001693 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001694 ++I;
1695
1696 const char *Begin = Body.data() + Pos +1;
1697 StringRef Argument(Begin, I - (Pos +1));
1698 unsigned Index = 0;
1699 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001700 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001701 break;
1702
Preston Gurd7b6f2032012-09-19 20:36:12 +00001703 if (Index == NParameters) {
1704 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1705 Pos += 3;
1706 else {
1707 OS << '\\' << Argument;
1708 Pos = I;
1709 }
1710 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001711 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001712 ie = A[Index].end(); it != ie; ++it)
1713 if (it->getKind() == AsmToken::String)
1714 OS << it->getStringContents();
1715 else
1716 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001717
Preston Gurd7b6f2032012-09-19 20:36:12 +00001718 Pos += 1 + Argument.size();
1719 }
Rafael Espindola65366442011-06-05 02:43:45 +00001720 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001721 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001722 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001723 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001724
Rafael Espindola65366442011-06-05 02:43:45 +00001725 return false;
1726}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001727
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001728MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001729 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001730 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001731 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1732 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001733{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001734}
1735
Preston Gurd7b6f2032012-09-19 20:36:12 +00001736static bool IsOperator(AsmToken::TokenKind kind)
1737{
1738 switch (kind)
1739 {
1740 default:
1741 return false;
1742 case AsmToken::Plus:
1743 case AsmToken::Minus:
1744 case AsmToken::Tilde:
1745 case AsmToken::Slash:
1746 case AsmToken::Star:
1747 case AsmToken::Dot:
1748 case AsmToken::Equal:
1749 case AsmToken::EqualEqual:
1750 case AsmToken::Pipe:
1751 case AsmToken::PipePipe:
1752 case AsmToken::Caret:
1753 case AsmToken::Amp:
1754 case AsmToken::AmpAmp:
1755 case AsmToken::Exclaim:
1756 case AsmToken::ExclaimEqual:
1757 case AsmToken::Percent:
1758 case AsmToken::Less:
1759 case AsmToken::LessEqual:
1760 case AsmToken::LessLess:
1761 case AsmToken::LessGreater:
1762 case AsmToken::Greater:
1763 case AsmToken::GreaterEqual:
1764 case AsmToken::GreaterGreater:
1765 return true;
1766 }
1767}
1768
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001769bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001770 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001771 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001772 unsigned AddTokens = 0;
1773
1774 // gas accepts arguments separated by whitespace, except on Darwin
1775 if (!IsDarwin)
1776 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001777
1778 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001779 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1780 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001781 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001782 }
1783
1784 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1785 // Spaces and commas cannot be mixed to delimit parameters
1786 if (ArgumentDelimiter == AsmToken::Eof)
1787 ArgumentDelimiter = AsmToken::Comma;
1788 else if (ArgumentDelimiter != AsmToken::Comma) {
1789 Lexer.setSkipSpace(true);
1790 return TokError("expected ' ' for macro argument separator");
1791 }
1792 break;
1793 }
1794
1795 if (Lexer.is(AsmToken::Space)) {
1796 Lex(); // Eat spaces
1797
1798 // Spaces can delimit parameters, but could also be part an expression.
1799 // If the token after a space is an operator, add the token and the next
1800 // one into this argument
1801 if (ArgumentDelimiter == AsmToken::Space ||
1802 ArgumentDelimiter == AsmToken::Eof) {
1803 if (IsOperator(Lexer.getKind())) {
1804 // Check to see whether the token is used as an operator,
1805 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001806 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001807 if (*NextChar == ' ')
1808 AddTokens = 2;
1809 }
1810
1811 if (!AddTokens && ParenLevel == 0) {
1812 if (ArgumentDelimiter == AsmToken::Eof &&
1813 !IsOperator(Lexer.getKind()))
1814 ArgumentDelimiter = AsmToken::Space;
1815 break;
1816 }
1817 }
1818 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001819
1820 // HandleMacroEntry relies on not advancing the lexer here
1821 // to be able to fill in the remaining default parameter values
1822 if (Lexer.is(AsmToken::EndOfStatement))
1823 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001824
1825 // Adjust the current parentheses level.
1826 if (Lexer.is(AsmToken::LParen))
1827 ++ParenLevel;
1828 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1829 --ParenLevel;
1830
1831 // Append the token to the current argument list.
1832 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001833 if (AddTokens)
1834 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001835 Lex();
1836 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001837
1838 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001839 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001840 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001841 return false;
1842}
1843
1844// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001845bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001846 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001847 // Argument delimiter is initially unknown. It will be set by
1848 // ParseMacroArgument()
1849 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001850
1851 // Parse two kinds of macro invocations:
1852 // - macros defined without any parameters accept an arbitrary number of them
1853 // - macros defined with parameters accept at most that many of them
1854 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1855 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001856 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001857
Preston Gurd7b6f2032012-09-19 20:36:12 +00001858 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001859 return true;
1860
Preston Gurd6c9176a2012-09-19 20:29:04 +00001861 if (!MA.empty() || !NParameters)
1862 A.push_back(MA);
1863 else if (NParameters) {
1864 if (!M->Parameters[Parameter].second.empty())
1865 A.push_back(M->Parameters[Parameter].second);
1866 }
Jim Grosbach97146442012-07-30 22:44:17 +00001867
Preston Gurd6c9176a2012-09-19 20:29:04 +00001868 // At the end of the statement, fill in remaining arguments that have
1869 // default values. If there aren't any, then the next argument is
1870 // required but missing
1871 if (Lexer.is(AsmToken::EndOfStatement)) {
1872 if (NParameters && Parameter < NParameters - 1) {
1873 if (M->Parameters[Parameter + 1].second.empty())
1874 return TokError("macro argument '" +
1875 Twine(M->Parameters[Parameter + 1].first) +
1876 "' is missing");
1877 else
1878 continue;
1879 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001880 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001881 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001882
1883 if (Lexer.is(AsmToken::Comma))
1884 Lex();
1885 }
1886 return TokError("Too many arguments");
1887}
1888
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001889const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1890 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1891 return (I == MacroMap.end()) ? NULL : I->getValue();
1892}
1893
1894void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1895 MacroMap[Name] = new MCAsmMacro(Macro);
1896}
1897
1898void AsmParser::UndefineMacro(StringRef Name) {
1899 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1900 if (I != MacroMap.end()) {
1901 delete I->getValue();
1902 MacroMap.erase(I);
1903 }
1904}
1905
1906bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001907 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1908 // this, although we should protect against infinite loops.
1909 if (ActiveMacros.size() == 20)
1910 return TokError("macros cannot be nested more than 20 levels deep");
1911
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001912 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001913 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001914 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001915
Jim Grosbach97146442012-07-30 22:44:17 +00001916 // Remove any trailing empty arguments. Do this after-the-fact as we have
1917 // to keep empty arguments in the middle of the list or positionality
1918 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001919 while (!A.empty() && A.back().empty())
1920 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001921
Rafael Espindola65366442011-06-05 02:43:45 +00001922 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1923 // to hold the macro body with substitutions.
1924 SmallString<256> Buf;
1925 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001926 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001927
Rafael Espindola8a403d32012-08-08 14:51:03 +00001928 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001929 return true;
1930
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001931 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001932 // instantiation.
1933 OS << ".endmacro\n";
1934
Rafael Espindola65366442011-06-05 02:43:45 +00001935 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001936 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001937
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001938 // Create the macro instantiation object and add to the current macro
1939 // instantiation stack.
1940 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001941 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001942 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001943 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001944 ActiveMacros.push_back(MI);
1945
1946 // Jump to the macro instantiation and prime the lexer.
1947 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1948 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1949 Lex();
1950
1951 return false;
1952}
1953
1954void AsmParser::HandleMacroExit() {
1955 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001956 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001957 Lex();
1958
1959 // Pop the instantiation entry.
1960 delete ActiveMacros.back();
1961 ActiveMacros.pop_back();
1962}
1963
Rafael Espindolae71cc862012-01-28 05:57:00 +00001964static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001965 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001966 case MCExpr::Binary: {
1967 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1968 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001969 break;
1970 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001971 case MCExpr::Target:
1972 case MCExpr::Constant:
1973 return false;
1974 case MCExpr::SymbolRef: {
1975 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001976 if (S.isVariable())
1977 return IsUsedIn(Sym, S.getVariableValue());
1978 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001979 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001980 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001981 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001982 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001983
1984 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001985}
1986
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001987bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1988 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001989 // FIXME: Use better location, we should use proper tokens.
1990 SMLoc EqualLoc = Lexer.getLoc();
1991
Daniel Dunbar821e3332009-08-31 08:09:28 +00001992 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001993 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001994 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001995
Rafael Espindolae71cc862012-01-28 05:57:00 +00001996 // Note: we don't count b as used in "a = b". This is to allow
1997 // a = b
1998 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001999
Daniel Dunbar3f872332009-07-28 16:08:33 +00002000 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002001 return TokError("unexpected token in assignment");
2002
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002003 // Error on assignment to '.'.
2004 if (Name == ".") {
2005 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2006 "(use '.space' or '.org').)"));
2007 }
2008
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002009 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002010 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002011
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002012 // Validate that the LHS is allowed to be a variable (either it has not been
2013 // used as a symbol, or it is an absolute symbol).
2014 MCSymbol *Sym = getContext().LookupSymbol(Name);
2015 if (Sym) {
2016 // Diagnose assignment to a label.
2017 //
2018 // FIXME: Diagnostics. Note the location of the definition as a label.
2019 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002020 if (IsUsedIn(Sym, Value))
2021 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2022 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002023 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002024 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2025 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002026 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002027 return Error(EqualLoc, "redefinition of '" + Name + "'");
2028 else if (!Sym->isVariable())
2029 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002030 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002031 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2032 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002033
2034 // Don't count these checks as uses.
2035 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002036 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002037 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002038
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002039 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002040
2041 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002042 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002043 if (NoDeadStrip)
2044 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2045
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002046
2047 return false;
2048}
2049
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002050/// ParseIdentifier:
2051/// ::= identifier
2052/// ::= string
2053bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002054 // The assembler has relaxed rules for accepting identifiers, in particular we
2055 // allow things like '.globl $foo', which would normally be separate
2056 // tokens. At this level, we have already lexed so we cannot (currently)
2057 // handle this as a context dependent token, instead we detect adjacent tokens
2058 // and return the combined identifier.
2059 if (Lexer.is(AsmToken::Dollar)) {
2060 SMLoc DollarLoc = getLexer().getLoc();
2061
2062 // Consume the dollar sign, and check for a following identifier.
2063 Lex();
2064 if (Lexer.isNot(AsmToken::Identifier))
2065 return true;
2066
2067 // We have a '$' followed by an identifier, make sure they are adjacent.
2068 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2069 return true;
2070
2071 // Construct the joined identifier and consume the token.
2072 Res = StringRef(DollarLoc.getPointer(),
2073 getTok().getIdentifier().size() + 1);
2074 Lex();
2075 return false;
2076 }
2077
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002078 if (Lexer.isNot(AsmToken::Identifier) &&
2079 Lexer.isNot(AsmToken::String))
2080 return true;
2081
Sean Callanan18b83232010-01-19 21:44:56 +00002082 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002083
Sean Callanan79ed1a82010-01-19 20:22:31 +00002084 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002085
2086 return false;
2087}
2088
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002089/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002090/// ::= .equ identifier ',' expression
2091/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002092/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002093bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002094 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002095
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002096 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002097 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002098
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002099 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002100 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002101 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002102
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002103 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002104}
2105
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002106bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002107 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002108
2109 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002110 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002111 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2112 if (Str[i] != '\\') {
2113 Data += Str[i];
2114 continue;
2115 }
2116
2117 // Recognize escaped characters. Note that this escape semantics currently
2118 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2119 ++i;
2120 if (i == e)
2121 return TokError("unexpected backslash at end of string");
2122
2123 // Recognize octal sequences.
2124 if ((unsigned) (Str[i] - '0') <= 7) {
2125 // Consume up to three octal characters.
2126 unsigned Value = Str[i] - '0';
2127
2128 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2129 ++i;
2130 Value = Value * 8 + (Str[i] - '0');
2131
2132 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2133 ++i;
2134 Value = Value * 8 + (Str[i] - '0');
2135 }
2136 }
2137
2138 if (Value > 255)
2139 return TokError("invalid octal escape sequence (out of range)");
2140
2141 Data += (unsigned char) Value;
2142 continue;
2143 }
2144
2145 // Otherwise recognize individual escapes.
2146 switch (Str[i]) {
2147 default:
2148 // Just reject invalid escape sequences for now.
2149 return TokError("invalid escape sequence (unrecognized character)");
2150
2151 case 'b': Data += '\b'; break;
2152 case 'f': Data += '\f'; break;
2153 case 'n': Data += '\n'; break;
2154 case 'r': Data += '\r'; break;
2155 case 't': Data += '\t'; break;
2156 case '"': Data += '"'; break;
2157 case '\\': Data += '\\'; break;
2158 }
2159 }
2160
2161 return false;
2162}
2163
Daniel Dunbara0d14262009-06-24 23:30:00 +00002164/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002165/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2166bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002167 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002168 CheckForValidSection();
2169
Daniel Dunbara0d14262009-06-24 23:30:00 +00002170 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002171 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002172 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002173
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002174 std::string Data;
2175 if (ParseEscapedString(Data))
2176 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002177
2178 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002179 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002180 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2181
Sean Callanan79ed1a82010-01-19 20:22:31 +00002182 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183
2184 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002185 break;
2186
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002187 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002188 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002189 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002190 }
2191 }
2192
Sean Callanan79ed1a82010-01-19 20:22:31 +00002193 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002194 return false;
2195}
2196
2197/// ParseDirectiveValue
2198/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2199bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002200 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002201 CheckForValidSection();
2202
Daniel Dunbara0d14262009-06-24 23:30:00 +00002203 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002204 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002205 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002206 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002207 return true;
2208
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002209 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002210 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2211 assert(Size <= 8 && "Invalid size");
2212 uint64_t IntValue = MCE->getValue();
2213 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2214 return Error(ExprLoc, "literal value out of range for directive");
2215 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2216 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002219 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002220 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002221
Daniel Dunbara0d14262009-06-24 23:30:00 +00002222 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002223 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002225 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002226 }
2227 }
2228
Sean Callanan79ed1a82010-01-19 20:22:31 +00002229 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 return false;
2231}
2232
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002233/// ParseDirectiveRealValue
2234/// ::= (.single | .double) [ expression (, expression)* ]
2235bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2237 CheckForValidSection();
2238
2239 for (;;) {
2240 // We don't truly support arithmetic on floating point expressions, so we
2241 // have to manually parse unary prefixes.
2242 bool IsNeg = false;
2243 if (getLexer().is(AsmToken::Minus)) {
2244 Lex();
2245 IsNeg = true;
2246 } else if (getLexer().is(AsmToken::Plus))
2247 Lex();
2248
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002249 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002250 getLexer().isNot(AsmToken::Real) &&
2251 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002252 return TokError("unexpected token in directive");
2253
2254 // Convert to an APFloat.
2255 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002256 StringRef IDVal = getTok().getString();
2257 if (getLexer().is(AsmToken::Identifier)) {
2258 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2259 Value = APFloat::getInf(Semantics);
2260 else if (!IDVal.compare_lower("nan"))
2261 Value = APFloat::getNaN(Semantics, false, ~0);
2262 else
2263 return TokError("invalid floating point literal");
2264 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002265 APFloat::opInvalidOp)
2266 return TokError("invalid floating point literal");
2267 if (IsNeg)
2268 Value.changeSign();
2269
2270 // Consume the numeric token.
2271 Lex();
2272
2273 // Emit the value as an integer.
2274 APInt AsInt = Value.bitcastToAPInt();
2275 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2276 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2277
2278 if (getLexer().is(AsmToken::EndOfStatement))
2279 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002280
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002281 if (getLexer().isNot(AsmToken::Comma))
2282 return TokError("unexpected token in directive");
2283 Lex();
2284 }
2285 }
2286
2287 Lex();
2288 return false;
2289}
2290
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002291/// ParseDirectiveZero
2292/// ::= .zero expression
2293bool AsmParser::ParseDirectiveZero() {
2294 CheckForValidSection();
2295
2296 int64_t NumBytes;
2297 if (ParseAbsoluteExpression(NumBytes))
2298 return true;
2299
Rafael Espindolae452b172010-10-05 19:42:57 +00002300 int64_t Val = 0;
2301 if (getLexer().is(AsmToken::Comma)) {
2302 Lex();
2303 if (ParseAbsoluteExpression(Val))
2304 return true;
2305 }
2306
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002307 if (getLexer().isNot(AsmToken::EndOfStatement))
2308 return TokError("unexpected token in '.zero' directive");
2309
2310 Lex();
2311
Rafael Espindolae452b172010-10-05 19:42:57 +00002312 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002313
2314 return false;
2315}
2316
Daniel Dunbara0d14262009-06-24 23:30:00 +00002317/// ParseDirectiveFill
2318/// ::= .fill expression , expression , expression
2319bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002320 CheckForValidSection();
2321
Daniel Dunbara0d14262009-06-24 23:30:00 +00002322 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002323 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002324 return true;
2325
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002326 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002327 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002328 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002329
Daniel Dunbara0d14262009-06-24 23:30:00 +00002330 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002331 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002332 return true;
2333
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002334 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002335 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002336 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002337
Daniel Dunbara0d14262009-06-24 23:30:00 +00002338 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002339 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002340 return true;
2341
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002342 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002343 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002344
Sean Callanan79ed1a82010-01-19 20:22:31 +00002345 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002346
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002347 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2348 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002349
2350 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002351 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002352
2353 return false;
2354}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002355
2356/// ParseDirectiveOrg
2357/// ::= .org expression [ , expression ]
2358bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002359 CheckForValidSection();
2360
Daniel Dunbar821e3332009-08-31 08:09:28 +00002361 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002362 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002363 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002364 return true;
2365
2366 // Parse optional fill expression.
2367 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002368 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2369 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002370 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002371 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002372
Daniel Dunbar475839e2009-06-29 20:37:27 +00002373 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002374 return true;
2375
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002376 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002377 return TokError("unexpected token in '.org' directive");
2378 }
2379
Sean Callanan79ed1a82010-01-19 20:22:31 +00002380 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002381
Jim Grosbachebd4c052012-01-27 00:37:08 +00002382 // Only limited forms of relocatable expressions are accepted here, it
2383 // has to be relative to the current section. The streamer will return
2384 // 'true' if the expression wasn't evaluatable.
2385 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2386 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002387
2388 return false;
2389}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002390
2391/// ParseDirectiveAlign
2392/// ::= {.align, ...} expression [ , expression [ , expression ]]
2393bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002394 CheckForValidSection();
2395
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002396 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002397 int64_t Alignment;
2398 if (ParseAbsoluteExpression(Alignment))
2399 return true;
2400
2401 SMLoc MaxBytesLoc;
2402 bool HasFillExpr = false;
2403 int64_t FillExpr = 0;
2404 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002405 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2406 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002407 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002408 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002409
2410 // The fill expression can be omitted while specifying a maximum number of
2411 // alignment bytes, e.g:
2412 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002413 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002414 HasFillExpr = true;
2415 if (ParseAbsoluteExpression(FillExpr))
2416 return true;
2417 }
2418
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002419 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2420 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002421 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002422 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002423
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002425 if (ParseAbsoluteExpression(MaxBytesToFill))
2426 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002427
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002428 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002429 return TokError("unexpected token in directive");
2430 }
2431 }
2432
Sean Callanan79ed1a82010-01-19 20:22:31 +00002433 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002434
Daniel Dunbar648ac512010-05-17 21:54:30 +00002435 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002436 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002437
2438 // Compute alignment in bytes.
2439 if (IsPow2) {
2440 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002441 if (Alignment >= 32) {
2442 Error(AlignmentLoc, "invalid alignment value");
2443 Alignment = 31;
2444 }
2445
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002446 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002447 }
2448
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002449 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002450 if (MaxBytesLoc.isValid()) {
2451 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002452 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2453 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002454 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002455 }
2456
2457 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002458 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2459 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002460 MaxBytesToFill = 0;
2461 }
2462 }
2463
Daniel Dunbar648ac512010-05-17 21:54:30 +00002464 // Check whether we should use optimal code alignment for this .align
2465 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002466 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002467 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2468 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002469 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002470 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002471 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002472 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2473 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002474 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002475
2476 return false;
2477}
2478
Eli Bendersky6ee13082013-01-15 22:59:42 +00002479/// ParseDirectiveFile
2480/// ::= .file [number] filename
2481/// ::= .file number directory filename
2482bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2483 // FIXME: I'm not sure what this is.
2484 int64_t FileNumber = -1;
2485 SMLoc FileNumberLoc = getLexer().getLoc();
2486 if (getLexer().is(AsmToken::Integer)) {
2487 FileNumber = getTok().getIntVal();
2488 Lex();
2489
2490 if (FileNumber < 1)
2491 return TokError("file number less than one");
2492 }
2493
2494 if (getLexer().isNot(AsmToken::String))
2495 return TokError("unexpected token in '.file' directive");
2496
2497 // Usually the directory and filename together, otherwise just the directory.
2498 StringRef Path = getTok().getString();
2499 Path = Path.substr(1, Path.size()-2);
2500 Lex();
2501
2502 StringRef Directory;
2503 StringRef Filename;
2504 if (getLexer().is(AsmToken::String)) {
2505 if (FileNumber == -1)
2506 return TokError("explicit path specified, but no file number");
2507 Filename = getTok().getString();
2508 Filename = Filename.substr(1, Filename.size()-2);
2509 Directory = Path;
2510 Lex();
2511 } else {
2512 Filename = Path;
2513 }
2514
2515 if (getLexer().isNot(AsmToken::EndOfStatement))
2516 return TokError("unexpected token in '.file' directive");
2517
2518 if (FileNumber == -1)
2519 getStreamer().EmitFileDirective(Filename);
2520 else {
2521 if (getContext().getGenDwarfForAssembly() == true)
2522 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2523 "used to generate dwarf debug info for assembly code");
2524
2525 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2526 Error(FileNumberLoc, "file number already allocated");
2527 }
2528
2529 return false;
2530}
2531
2532/// ParseDirectiveLine
2533/// ::= .line [number]
2534bool AsmParser::ParseDirectiveLine() {
2535 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2536 if (getLexer().isNot(AsmToken::Integer))
2537 return TokError("unexpected token in '.line' directive");
2538
2539 int64_t LineNumber = getTok().getIntVal();
2540 (void) LineNumber;
2541 Lex();
2542
2543 // FIXME: Do something with the .line.
2544 }
2545
2546 if (getLexer().isNot(AsmToken::EndOfStatement))
2547 return TokError("unexpected token in '.line' directive");
2548
2549 return false;
2550}
2551
2552/// ParseDirectiveLoc
2553/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2554/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2555/// The first number is a file number, must have been previously assigned with
2556/// a .file directive, the second number is the line number and optionally the
2557/// third number is a column position (zero if not specified). The remaining
2558/// optional items are .loc sub-directives.
2559bool AsmParser::ParseDirectiveLoc() {
2560 if (getLexer().isNot(AsmToken::Integer))
2561 return TokError("unexpected token in '.loc' directive");
2562 int64_t FileNumber = getTok().getIntVal();
2563 if (FileNumber < 1)
2564 return TokError("file number less than one in '.loc' directive");
2565 if (!getContext().isValidDwarfFileNumber(FileNumber))
2566 return TokError("unassigned file number in '.loc' directive");
2567 Lex();
2568
2569 int64_t LineNumber = 0;
2570 if (getLexer().is(AsmToken::Integer)) {
2571 LineNumber = getTok().getIntVal();
2572 if (LineNumber < 1)
2573 return TokError("line number less than one in '.loc' directive");
2574 Lex();
2575 }
2576
2577 int64_t ColumnPos = 0;
2578 if (getLexer().is(AsmToken::Integer)) {
2579 ColumnPos = getTok().getIntVal();
2580 if (ColumnPos < 0)
2581 return TokError("column position less than zero in '.loc' directive");
2582 Lex();
2583 }
2584
2585 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2586 unsigned Isa = 0;
2587 int64_t Discriminator = 0;
2588 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2589 for (;;) {
2590 if (getLexer().is(AsmToken::EndOfStatement))
2591 break;
2592
2593 StringRef Name;
2594 SMLoc Loc = getTok().getLoc();
2595 if (ParseIdentifier(Name))
2596 return TokError("unexpected token in '.loc' directive");
2597
2598 if (Name == "basic_block")
2599 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2600 else if (Name == "prologue_end")
2601 Flags |= DWARF2_FLAG_PROLOGUE_END;
2602 else if (Name == "epilogue_begin")
2603 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2604 else if (Name == "is_stmt") {
2605 Loc = getTok().getLoc();
2606 const MCExpr *Value;
2607 if (ParseExpression(Value))
2608 return true;
2609 // The expression must be the constant 0 or 1.
2610 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2611 int Value = MCE->getValue();
2612 if (Value == 0)
2613 Flags &= ~DWARF2_FLAG_IS_STMT;
2614 else if (Value == 1)
2615 Flags |= DWARF2_FLAG_IS_STMT;
2616 else
2617 return Error(Loc, "is_stmt value not 0 or 1");
2618 }
2619 else {
2620 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2621 }
2622 }
2623 else if (Name == "isa") {
2624 Loc = getTok().getLoc();
2625 const MCExpr *Value;
2626 if (ParseExpression(Value))
2627 return true;
2628 // The expression must be a constant greater or equal to 0.
2629 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2630 int Value = MCE->getValue();
2631 if (Value < 0)
2632 return Error(Loc, "isa number less than zero");
2633 Isa = Value;
2634 }
2635 else {
2636 return Error(Loc, "isa number not a constant value");
2637 }
2638 }
2639 else if (Name == "discriminator") {
2640 if (ParseAbsoluteExpression(Discriminator))
2641 return true;
2642 }
2643 else {
2644 return Error(Loc, "unknown sub-directive in '.loc' directive");
2645 }
2646
2647 if (getLexer().is(AsmToken::EndOfStatement))
2648 break;
2649 }
2650 }
2651
2652 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2653 Isa, Discriminator, StringRef());
2654
2655 return false;
2656}
2657
2658/// ParseDirectiveStabs
2659/// ::= .stabs string, number, number, number
2660bool AsmParser::ParseDirectiveStabs() {
2661 return TokError("unsupported directive '.stabs'");
2662}
2663
2664/// ParseDirectiveCFISections
2665/// ::= .cfi_sections section [, section]
2666bool AsmParser::ParseDirectiveCFISections() {
2667 StringRef Name;
2668 bool EH = false;
2669 bool Debug = false;
2670
2671 if (ParseIdentifier(Name))
2672 return TokError("Expected an identifier");
2673
2674 if (Name == ".eh_frame")
2675 EH = true;
2676 else if (Name == ".debug_frame")
2677 Debug = true;
2678
2679 if (getLexer().is(AsmToken::Comma)) {
2680 Lex();
2681
2682 if (ParseIdentifier(Name))
2683 return TokError("Expected an identifier");
2684
2685 if (Name == ".eh_frame")
2686 EH = true;
2687 else if (Name == ".debug_frame")
2688 Debug = true;
2689 }
2690
2691 getStreamer().EmitCFISections(EH, Debug);
2692 return false;
2693}
2694
2695/// ParseDirectiveCFIStartProc
2696/// ::= .cfi_startproc
2697bool AsmParser::ParseDirectiveCFIStartProc() {
2698 getStreamer().EmitCFIStartProc();
2699 return false;
2700}
2701
2702/// ParseDirectiveCFIEndProc
2703/// ::= .cfi_endproc
2704bool AsmParser::ParseDirectiveCFIEndProc() {
2705 getStreamer().EmitCFIEndProc();
2706 return false;
2707}
2708
2709/// ParseRegisterOrRegisterNumber - parse register name or number.
2710bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2711 SMLoc DirectiveLoc) {
2712 unsigned RegNo;
2713
2714 if (getLexer().isNot(AsmToken::Integer)) {
2715 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2716 return true;
2717 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2718 } else
2719 return ParseAbsoluteExpression(Register);
2720
2721 return false;
2722}
2723
2724/// ParseDirectiveCFIDefCfa
2725/// ::= .cfi_def_cfa register, offset
2726bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2727 int64_t Register = 0;
2728 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2729 return true;
2730
2731 if (getLexer().isNot(AsmToken::Comma))
2732 return TokError("unexpected token in directive");
2733 Lex();
2734
2735 int64_t Offset = 0;
2736 if (ParseAbsoluteExpression(Offset))
2737 return true;
2738
2739 getStreamer().EmitCFIDefCfa(Register, Offset);
2740 return false;
2741}
2742
2743/// ParseDirectiveCFIDefCfaOffset
2744/// ::= .cfi_def_cfa_offset offset
2745bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2746 int64_t Offset = 0;
2747 if (ParseAbsoluteExpression(Offset))
2748 return true;
2749
2750 getStreamer().EmitCFIDefCfaOffset(Offset);
2751 return false;
2752}
2753
2754/// ParseDirectiveCFIRegister
2755/// ::= .cfi_register register, register
2756bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2757 int64_t Register1 = 0;
2758 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2759 return true;
2760
2761 if (getLexer().isNot(AsmToken::Comma))
2762 return TokError("unexpected token in directive");
2763 Lex();
2764
2765 int64_t Register2 = 0;
2766 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2767 return true;
2768
2769 getStreamer().EmitCFIRegister(Register1, Register2);
2770 return false;
2771}
2772
2773/// ParseDirectiveCFIAdjustCfaOffset
2774/// ::= .cfi_adjust_cfa_offset adjustment
2775bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2776 int64_t Adjustment = 0;
2777 if (ParseAbsoluteExpression(Adjustment))
2778 return true;
2779
2780 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2781 return false;
2782}
2783
2784/// ParseDirectiveCFIDefCfaRegister
2785/// ::= .cfi_def_cfa_register register
2786bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2787 int64_t Register = 0;
2788 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2789 return true;
2790
2791 getStreamer().EmitCFIDefCfaRegister(Register);
2792 return false;
2793}
2794
2795/// ParseDirectiveCFIOffset
2796/// ::= .cfi_offset register, offset
2797bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2798 int64_t Register = 0;
2799 int64_t Offset = 0;
2800
2801 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2802 return true;
2803
2804 if (getLexer().isNot(AsmToken::Comma))
2805 return TokError("unexpected token in directive");
2806 Lex();
2807
2808 if (ParseAbsoluteExpression(Offset))
2809 return true;
2810
2811 getStreamer().EmitCFIOffset(Register, Offset);
2812 return false;
2813}
2814
2815/// ParseDirectiveCFIRelOffset
2816/// ::= .cfi_rel_offset register, offset
2817bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2818 int64_t Register = 0;
2819
2820 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2821 return true;
2822
2823 if (getLexer().isNot(AsmToken::Comma))
2824 return TokError("unexpected token in directive");
2825 Lex();
2826
2827 int64_t Offset = 0;
2828 if (ParseAbsoluteExpression(Offset))
2829 return true;
2830
2831 getStreamer().EmitCFIRelOffset(Register, Offset);
2832 return false;
2833}
2834
2835static bool isValidEncoding(int64_t Encoding) {
2836 if (Encoding & ~0xff)
2837 return false;
2838
2839 if (Encoding == dwarf::DW_EH_PE_omit)
2840 return true;
2841
2842 const unsigned Format = Encoding & 0xf;
2843 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2844 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2845 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2846 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2847 return false;
2848
2849 const unsigned Application = Encoding & 0x70;
2850 if (Application != dwarf::DW_EH_PE_absptr &&
2851 Application != dwarf::DW_EH_PE_pcrel)
2852 return false;
2853
2854 return true;
2855}
2856
2857/// ParseDirectiveCFIPersonalityOrLsda
2858/// IsPersonality true for cfi_personality, false for cfi_lsda
2859/// ::= .cfi_personality encoding, [symbol_name]
2860/// ::= .cfi_lsda encoding, [symbol_name]
2861bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2862 int64_t Encoding = 0;
2863 if (ParseAbsoluteExpression(Encoding))
2864 return true;
2865 if (Encoding == dwarf::DW_EH_PE_omit)
2866 return false;
2867
2868 if (!isValidEncoding(Encoding))
2869 return TokError("unsupported encoding.");
2870
2871 if (getLexer().isNot(AsmToken::Comma))
2872 return TokError("unexpected token in directive");
2873 Lex();
2874
2875 StringRef Name;
2876 if (ParseIdentifier(Name))
2877 return TokError("expected identifier in directive");
2878
2879 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2880
2881 if (IsPersonality)
2882 getStreamer().EmitCFIPersonality(Sym, Encoding);
2883 else
2884 getStreamer().EmitCFILsda(Sym, Encoding);
2885 return false;
2886}
2887
2888/// ParseDirectiveCFIRememberState
2889/// ::= .cfi_remember_state
2890bool AsmParser::ParseDirectiveCFIRememberState() {
2891 getStreamer().EmitCFIRememberState();
2892 return false;
2893}
2894
2895/// ParseDirectiveCFIRestoreState
2896/// ::= .cfi_remember_state
2897bool AsmParser::ParseDirectiveCFIRestoreState() {
2898 getStreamer().EmitCFIRestoreState();
2899 return false;
2900}
2901
2902/// ParseDirectiveCFISameValue
2903/// ::= .cfi_same_value register
2904bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2905 int64_t Register = 0;
2906
2907 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2908 return true;
2909
2910 getStreamer().EmitCFISameValue(Register);
2911 return false;
2912}
2913
2914/// ParseDirectiveCFIRestore
2915/// ::= .cfi_restore register
2916bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2917 int64_t Register = 0;
2918 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2919 return true;
2920
2921 getStreamer().EmitCFIRestore(Register);
2922 return false;
2923}
2924
2925/// ParseDirectiveCFIEscape
2926/// ::= .cfi_escape expression[,...]
2927bool AsmParser::ParseDirectiveCFIEscape() {
2928 std::string Values;
2929 int64_t CurrValue;
2930 if (ParseAbsoluteExpression(CurrValue))
2931 return true;
2932
2933 Values.push_back((uint8_t)CurrValue);
2934
2935 while (getLexer().is(AsmToken::Comma)) {
2936 Lex();
2937
2938 if (ParseAbsoluteExpression(CurrValue))
2939 return true;
2940
2941 Values.push_back((uint8_t)CurrValue);
2942 }
2943
2944 getStreamer().EmitCFIEscape(Values);
2945 return false;
2946}
2947
2948/// ParseDirectiveCFISignalFrame
2949/// ::= .cfi_signal_frame
2950bool AsmParser::ParseDirectiveCFISignalFrame() {
2951 if (getLexer().isNot(AsmToken::EndOfStatement))
2952 return Error(getLexer().getLoc(),
2953 "unexpected token in '.cfi_signal_frame'");
2954
2955 getStreamer().EmitCFISignalFrame();
2956 return false;
2957}
2958
2959/// ParseDirectiveCFIUndefined
2960/// ::= .cfi_undefined register
2961bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2962 int64_t Register = 0;
2963
2964 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2965 return true;
2966
2967 getStreamer().EmitCFIUndefined(Register);
2968 return false;
2969}
2970
2971/// ParseDirectiveMacrosOnOff
2972/// ::= .macros_on
2973/// ::= .macros_off
2974bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2975 if (getLexer().isNot(AsmToken::EndOfStatement))
2976 return Error(getLexer().getLoc(),
2977 "unexpected token in '" + Directive + "' directive");
2978
2979 SetMacrosEnabled(Directive == ".macros_on");
2980 return false;
2981}
2982
2983/// ParseDirectiveMacro
2984/// ::= .macro name [parameters]
2985bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2986 StringRef Name;
2987 if (ParseIdentifier(Name))
2988 return TokError("expected identifier in '.macro' directive");
2989
2990 MCAsmMacroParameters Parameters;
2991 // Argument delimiter is initially unknown. It will be set by
2992 // ParseMacroArgument()
2993 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2994 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2995 for (;;) {
2996 MCAsmMacroParameter Parameter;
2997 if (ParseIdentifier(Parameter.first))
2998 return TokError("expected identifier in '.macro' directive");
2999
3000 if (getLexer().is(AsmToken::Equal)) {
3001 Lex();
3002 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3003 return true;
3004 }
3005
3006 Parameters.push_back(Parameter);
3007
3008 if (getLexer().is(AsmToken::Comma))
3009 Lex();
3010 else if (getLexer().is(AsmToken::EndOfStatement))
3011 break;
3012 }
3013 }
3014
3015 // Eat the end of statement.
3016 Lex();
3017
3018 AsmToken EndToken, StartToken = getTok();
3019
3020 // Lex the macro definition.
3021 for (;;) {
3022 // Check whether we have reached the end of the file.
3023 if (getLexer().is(AsmToken::Eof))
3024 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3025
3026 // Otherwise, check whether we have reach the .endmacro.
3027 if (getLexer().is(AsmToken::Identifier) &&
3028 (getTok().getIdentifier() == ".endm" ||
3029 getTok().getIdentifier() == ".endmacro")) {
3030 EndToken = getTok();
3031 Lex();
3032 if (getLexer().isNot(AsmToken::EndOfStatement))
3033 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3034 "' directive");
3035 break;
3036 }
3037
3038 // Otherwise, scan til the end of the statement.
3039 EatToEndOfStatement();
3040 }
3041
3042 if (LookupMacro(Name)) {
3043 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3044 }
3045
3046 const char *BodyStart = StartToken.getLoc().getPointer();
3047 const char *BodyEnd = EndToken.getLoc().getPointer();
3048 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003049 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003050 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3051 return false;
3052}
3053
Kevin Enderby221514e2013-01-22 21:44:53 +00003054/// CheckForBadMacro
3055///
3056/// With the support added for named parameters there may be code out there that
3057/// is transitioning from positional parameters. In versions of gas that did
3058/// not support named parameters they would be ignored on the macro defintion.
3059/// But to support both styles of parameters this is not possible so if a macro
3060/// defintion has named parameters but does not use them and has what appears
3061/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3062/// warning that the positional parameter found in body which have no effect.
3063/// Hoping the developer will either remove the named parameters from the macro
3064/// definiton so the positional parameters get used if that was what was
3065/// intended or change the macro to use the named parameters. It is possible
3066/// this warning will trigger when the none of the named parameters are used
3067/// and the strings like $1 are infact to simply to be passed trough unchanged.
3068void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3069 StringRef Body,
3070 MCAsmMacroParameters Parameters) {
3071 // If this macro is not defined with named parameters the warning we are
3072 // checking for here doesn't apply.
3073 unsigned NParameters = Parameters.size();
3074 if (NParameters == 0)
3075 return;
3076
3077 bool NamedParametersFound = false;
3078 bool PositionalParametersFound = false;
3079
3080 // Look at the body of the macro for use of both the named parameters and what
3081 // are likely to be positional parameters. This is what expandMacro() is
3082 // doing when it finds the parameters in the body.
3083 while (!Body.empty()) {
3084 // Scan for the next possible parameter.
3085 std::size_t End = Body.size(), Pos = 0;
3086 for (; Pos != End; ++Pos) {
3087 // Check for a substitution or escape.
3088 // This macro is defined with parameters, look for \foo, \bar, etc.
3089 if (Body[Pos] == '\\' && Pos + 1 != End)
3090 break;
3091
3092 // This macro should have parameters, but look for $0, $1, ..., $n too.
3093 if (Body[Pos] != '$' || Pos + 1 == End)
3094 continue;
3095 char Next = Body[Pos + 1];
3096 if (Next == '$' || Next == 'n' || isdigit(Next))
3097 break;
3098 }
3099
3100 // Check if we reached the end.
3101 if (Pos == End)
3102 break;
3103
3104 if (Body[Pos] == '$') {
3105 switch (Body[Pos+1]) {
3106 // $$ => $
3107 case '$':
3108 break;
3109
3110 // $n => number of arguments
3111 case 'n':
3112 PositionalParametersFound = true;
3113 break;
3114
3115 // $[0-9] => argument
3116 default: {
3117 PositionalParametersFound = true;
3118 break;
3119 }
3120 }
3121 Pos += 2;
3122 } else {
3123 unsigned I = Pos + 1;
3124 while (isIdentifierChar(Body[I]) && I + 1 != End)
3125 ++I;
3126
3127 const char *Begin = Body.data() + Pos +1;
3128 StringRef Argument(Begin, I - (Pos +1));
3129 unsigned Index = 0;
3130 for (; Index < NParameters; ++Index)
3131 if (Parameters[Index].first == Argument)
3132 break;
3133
3134 if (Index == NParameters) {
3135 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3136 Pos += 3;
3137 else {
3138 Pos = I;
3139 }
3140 } else {
3141 NamedParametersFound = true;
3142 Pos += 1 + Argument.size();
3143 }
3144 }
3145 // Update the scan point.
3146 Body = Body.substr(Pos);
3147 }
3148
3149 if (!NamedParametersFound && PositionalParametersFound)
3150 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3151 "used in macro body, possible positional parameter "
3152 "found in body which will have no effect");
3153}
3154
Eli Bendersky6ee13082013-01-15 22:59:42 +00003155/// ParseDirectiveEndMacro
3156/// ::= .endm
3157/// ::= .endmacro
3158bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3159 if (getLexer().isNot(AsmToken::EndOfStatement))
3160 return TokError("unexpected token in '" + Directive + "' directive");
3161
3162 // If we are inside a macro instantiation, terminate the current
3163 // instantiation.
3164 if (InsideMacroInstantiation()) {
3165 HandleMacroExit();
3166 return false;
3167 }
3168
3169 // Otherwise, this .endmacro is a stray entry in the file; well formed
3170 // .endmacro directives are handled during the macro definition parsing.
3171 return TokError("unexpected '" + Directive + "' in file, "
3172 "no current macro definition");
3173}
3174
3175/// ParseDirectivePurgeMacro
3176/// ::= .purgem
3177bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3178 StringRef Name;
3179 if (ParseIdentifier(Name))
3180 return TokError("expected identifier in '.purgem' directive");
3181
3182 if (getLexer().isNot(AsmToken::EndOfStatement))
3183 return TokError("unexpected token in '.purgem' directive");
3184
3185 if (!LookupMacro(Name))
3186 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3187
3188 UndefineMacro(Name);
3189 return false;
3190}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003191
3192/// ParseDirectiveBundleAlignMode
3193/// ::= {.bundle_align_mode} expression
3194bool AsmParser::ParseDirectiveBundleAlignMode() {
3195 CheckForValidSection();
3196
3197 // Expect a single argument: an expression that evaluates to a constant
3198 // in the inclusive range 0-30.
3199 SMLoc ExprLoc = getLexer().getLoc();
3200 int64_t AlignSizePow2;
3201 if (ParseAbsoluteExpression(AlignSizePow2))
3202 return true;
3203 else if (getLexer().isNot(AsmToken::EndOfStatement))
3204 return TokError("unexpected token after expression in"
3205 " '.bundle_align_mode' directive");
3206 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3207 return Error(ExprLoc,
3208 "invalid bundle alignment size (expected between 0 and 30)");
3209
3210 Lex();
3211
3212 // Because of AlignSizePow2's verified range we can safely truncate it to
3213 // unsigned.
3214 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3215 return false;
3216}
3217
3218/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003219/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003220bool AsmParser::ParseDirectiveBundleLock() {
3221 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003222 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003223
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003224 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3225 StringRef Option;
3226 SMLoc Loc = getTok().getLoc();
3227 const char *kInvalidOptionError =
3228 "invalid option for '.bundle_lock' directive";
3229
3230 if (ParseIdentifier(Option))
3231 return Error(Loc, kInvalidOptionError);
3232
3233 if (Option != "align_to_end")
3234 return Error(Loc, kInvalidOptionError);
3235 else if (getLexer().isNot(AsmToken::EndOfStatement))
3236 return Error(Loc,
3237 "unexpected token after '.bundle_lock' directive option");
3238 AlignToEnd = true;
3239 }
3240
Eli Bendersky4766ef42012-12-20 19:05:53 +00003241 Lex();
3242
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003243 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003244 return false;
3245}
3246
3247/// ParseDirectiveBundleLock
3248/// ::= {.bundle_lock}
3249bool AsmParser::ParseDirectiveBundleUnlock() {
3250 CheckForValidSection();
3251
3252 if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return TokError("unexpected token in '.bundle_unlock' directive");
3254 Lex();
3255
3256 getStreamer().EmitBundleUnlock();
3257 return false;
3258}
3259
Eli Bendersky6ee13082013-01-15 22:59:42 +00003260/// ParseDirectiveSpace
3261/// ::= (.skip | .space) expression [ , expression ]
3262bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3263 CheckForValidSection();
3264
3265 int64_t NumBytes;
3266 if (ParseAbsoluteExpression(NumBytes))
3267 return true;
3268
3269 int64_t FillExpr = 0;
3270 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3271 if (getLexer().isNot(AsmToken::Comma))
3272 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3273 Lex();
3274
3275 if (ParseAbsoluteExpression(FillExpr))
3276 return true;
3277
3278 if (getLexer().isNot(AsmToken::EndOfStatement))
3279 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3280 }
3281
3282 Lex();
3283
3284 if (NumBytes <= 0)
3285 return TokError("invalid number of bytes in '" +
3286 Twine(IDVal) + "' directive");
3287
3288 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3289 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3290
3291 return false;
3292}
3293
3294/// ParseDirectiveLEB128
3295/// ::= (.sleb128 | .uleb128) expression
3296bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3297 CheckForValidSection();
3298 const MCExpr *Value;
3299
3300 if (ParseExpression(Value))
3301 return true;
3302
3303 if (getLexer().isNot(AsmToken::EndOfStatement))
3304 return TokError("unexpected token in directive");
3305
3306 if (Signed)
3307 getStreamer().EmitSLEB128Value(Value);
3308 else
3309 getStreamer().EmitULEB128Value(Value);
3310
3311 return false;
3312}
3313
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003314/// ParseDirectiveSymbolAttribute
3315/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003316bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003317 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003318 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003319 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003320 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003321
3322 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003323 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003324
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003325 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003326
Jim Grosbach10ec6502011-09-15 17:56:49 +00003327 // Assembler local symbols don't make any sense here. Complain loudly.
3328 if (Sym->isTemporary())
3329 return Error(Loc, "non-local symbol required in directive");
3330
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003331 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003332
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003333 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003334 break;
3335
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003336 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003337 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003338 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003339 }
3340 }
3341
Sean Callanan79ed1a82010-01-19 20:22:31 +00003342 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003343 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003344}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003345
3346/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003347/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3348bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003349 CheckForValidSection();
3350
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003351 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003352 StringRef Name;
3353 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003354 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003355
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003356 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003357 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003358
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003359 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003360 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003361 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003362
3363 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003364 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003365 if (ParseAbsoluteExpression(Size))
3366 return true;
3367
3368 int64_t Pow2Alignment = 0;
3369 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003370 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003371 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003372 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003373 if (ParseAbsoluteExpression(Pow2Alignment))
3374 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003375
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003376 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3377 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003378 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3379
Chris Lattner258281d2010-01-19 06:22:22 +00003380 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003381 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3382 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003383 if (!isPowerOf2_64(Pow2Alignment))
3384 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3385 Pow2Alignment = Log2_64(Pow2Alignment);
3386 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003387 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003388
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003389 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003390 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003391
Sean Callanan79ed1a82010-01-19 20:22:31 +00003392 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003393
Chris Lattner1fc3d752009-07-09 17:25:12 +00003394 // NOTE: a size of zero for a .comm should create a undefined symbol
3395 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003396 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003397 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3398 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003399
Eric Christopherc260a3e2010-05-14 01:38:54 +00003400 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003401 // may internally end up wanting an alignment in bytes.
3402 // FIXME: Diagnose overflow.
3403 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003404 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3405 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003406
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003407 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003408 return Error(IDLoc, "invalid symbol redefinition");
3409
Chris Lattner1fc3d752009-07-09 17:25:12 +00003410 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003411 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003412 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003413 return false;
3414 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003415
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003416 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003417 return false;
3418}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003419
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003420/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003421/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003422bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003423 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003424 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003425
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003426 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003427 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003428 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003429
Sean Callanan79ed1a82010-01-19 20:22:31 +00003430 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003431
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003432 if (Str.empty())
3433 Error(Loc, ".abort detected. Assembly stopping.");
3434 else
3435 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003436 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003437
3438 return false;
3439}
Kevin Enderby71148242009-07-14 21:35:03 +00003440
Kevin Enderby1f049b22009-07-14 23:21:55 +00003441/// ParseDirectiveInclude
3442/// ::= .include "filename"
3443bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003444 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003445 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003446
Sean Callanan18b83232010-01-19 21:44:56 +00003447 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003448 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003449 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003450
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003451 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003452 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003453
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003454 // Strip the quotes.
3455 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003456
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003457 // Attempt to switch the lexer to the included file before consuming the end
3458 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003459 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003460 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003461 return true;
3462 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003463
3464 return false;
3465}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003466
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003467/// ParseDirectiveIncbin
3468/// ::= .incbin "filename"
3469bool AsmParser::ParseDirectiveIncbin() {
3470 if (getLexer().isNot(AsmToken::String))
3471 return TokError("expected string in '.incbin' directive");
3472
3473 std::string Filename = getTok().getString();
3474 SMLoc IncbinLoc = getLexer().getLoc();
3475 Lex();
3476
3477 if (getLexer().isNot(AsmToken::EndOfStatement))
3478 return TokError("unexpected token in '.incbin' directive");
3479
3480 // Strip the quotes.
3481 Filename = Filename.substr(1, Filename.size()-2);
3482
3483 // Attempt to process the included file.
3484 if (ProcessIncbinFile(Filename)) {
3485 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3486 return true;
3487 }
3488
3489 return false;
3490}
3491
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003492/// ParseDirectiveIf
3493/// ::= .if expression
3494bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003495 TheCondStack.push_back(TheCondState);
3496 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003497 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003498 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003499 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003500 int64_t ExprValue;
3501 if (ParseAbsoluteExpression(ExprValue))
3502 return true;
3503
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003504 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003505 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003506
Sean Callanan79ed1a82010-01-19 20:22:31 +00003507 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003508
3509 TheCondState.CondMet = ExprValue;
3510 TheCondState.Ignore = !TheCondState.CondMet;
3511 }
3512
3513 return false;
3514}
3515
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003516/// ParseDirectiveIfb
3517/// ::= .ifb string
3518bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3519 TheCondStack.push_back(TheCondState);
3520 TheCondState.TheCond = AsmCond::IfCond;
3521
Benjamin Kramer29739e72012-05-12 16:52:21 +00003522 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003523 EatToEndOfStatement();
3524 } else {
3525 StringRef Str = ParseStringToEndOfStatement();
3526
3527 if (getLexer().isNot(AsmToken::EndOfStatement))
3528 return TokError("unexpected token in '.ifb' directive");
3529
3530 Lex();
3531
3532 TheCondState.CondMet = ExpectBlank == Str.empty();
3533 TheCondState.Ignore = !TheCondState.CondMet;
3534 }
3535
3536 return false;
3537}
3538
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003539/// ParseDirectiveIfc
3540/// ::= .ifc string1, string2
3541bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3542 TheCondStack.push_back(TheCondState);
3543 TheCondState.TheCond = AsmCond::IfCond;
3544
Benjamin Kramer29739e72012-05-12 16:52:21 +00003545 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003546 EatToEndOfStatement();
3547 } else {
3548 StringRef Str1 = ParseStringToComma();
3549
3550 if (getLexer().isNot(AsmToken::Comma))
3551 return TokError("unexpected token in '.ifc' directive");
3552
3553 Lex();
3554
3555 StringRef Str2 = ParseStringToEndOfStatement();
3556
3557 if (getLexer().isNot(AsmToken::EndOfStatement))
3558 return TokError("unexpected token in '.ifc' directive");
3559
3560 Lex();
3561
3562 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3563 TheCondState.Ignore = !TheCondState.CondMet;
3564 }
3565
3566 return false;
3567}
3568
3569/// ParseDirectiveIfdef
3570/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003571bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3572 StringRef Name;
3573 TheCondStack.push_back(TheCondState);
3574 TheCondState.TheCond = AsmCond::IfCond;
3575
3576 if (TheCondState.Ignore) {
3577 EatToEndOfStatement();
3578 } else {
3579 if (ParseIdentifier(Name))
3580 return TokError("expected identifier after '.ifdef'");
3581
3582 Lex();
3583
3584 MCSymbol *Sym = getContext().LookupSymbol(Name);
3585
3586 if (expect_defined)
3587 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3588 else
3589 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3590 TheCondState.Ignore = !TheCondState.CondMet;
3591 }
3592
3593 return false;
3594}
3595
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003596/// ParseDirectiveElseIf
3597/// ::= .elseif expression
3598bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3599 if (TheCondState.TheCond != AsmCond::IfCond &&
3600 TheCondState.TheCond != AsmCond::ElseIfCond)
3601 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3602 " an .elseif");
3603 TheCondState.TheCond = AsmCond::ElseIfCond;
3604
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003605 bool LastIgnoreState = false;
3606 if (!TheCondStack.empty())
3607 LastIgnoreState = TheCondStack.back().Ignore;
3608 if (LastIgnoreState || TheCondState.CondMet) {
3609 TheCondState.Ignore = true;
3610 EatToEndOfStatement();
3611 }
3612 else {
3613 int64_t ExprValue;
3614 if (ParseAbsoluteExpression(ExprValue))
3615 return true;
3616
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003617 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003618 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003619
Sean Callanan79ed1a82010-01-19 20:22:31 +00003620 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003621 TheCondState.CondMet = ExprValue;
3622 TheCondState.Ignore = !TheCondState.CondMet;
3623 }
3624
3625 return false;
3626}
3627
3628/// ParseDirectiveElse
3629/// ::= .else
3630bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003631 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003632 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003633
Sean Callanan79ed1a82010-01-19 20:22:31 +00003634 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003635
3636 if (TheCondState.TheCond != AsmCond::IfCond &&
3637 TheCondState.TheCond != AsmCond::ElseIfCond)
3638 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3639 ".elseif");
3640 TheCondState.TheCond = AsmCond::ElseCond;
3641 bool LastIgnoreState = false;
3642 if (!TheCondStack.empty())
3643 LastIgnoreState = TheCondStack.back().Ignore;
3644 if (LastIgnoreState || TheCondState.CondMet)
3645 TheCondState.Ignore = true;
3646 else
3647 TheCondState.Ignore = false;
3648
3649 return false;
3650}
3651
3652/// ParseDirectiveEndIf
3653/// ::= .endif
3654bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003655 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003656 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003657
Sean Callanan79ed1a82010-01-19 20:22:31 +00003658 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003659
3660 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3661 TheCondStack.empty())
3662 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3663 ".else");
3664 if (!TheCondStack.empty()) {
3665 TheCondState = TheCondStack.back();
3666 TheCondStack.pop_back();
3667 }
3668
3669 return false;
3670}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003671
Eli Bendersky6ee13082013-01-15 22:59:42 +00003672void AsmParser::initializeDirectiveKindMap() {
3673 DirectiveKindMap[".set"] = DK_SET;
3674 DirectiveKindMap[".equ"] = DK_EQU;
3675 DirectiveKindMap[".equiv"] = DK_EQUIV;
3676 DirectiveKindMap[".ascii"] = DK_ASCII;
3677 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3678 DirectiveKindMap[".string"] = DK_STRING;
3679 DirectiveKindMap[".byte"] = DK_BYTE;
3680 DirectiveKindMap[".short"] = DK_SHORT;
3681 DirectiveKindMap[".value"] = DK_VALUE;
3682 DirectiveKindMap[".2byte"] = DK_2BYTE;
3683 DirectiveKindMap[".long"] = DK_LONG;
3684 DirectiveKindMap[".int"] = DK_INT;
3685 DirectiveKindMap[".4byte"] = DK_4BYTE;
3686 DirectiveKindMap[".quad"] = DK_QUAD;
3687 DirectiveKindMap[".8byte"] = DK_8BYTE;
3688 DirectiveKindMap[".single"] = DK_SINGLE;
3689 DirectiveKindMap[".float"] = DK_FLOAT;
3690 DirectiveKindMap[".double"] = DK_DOUBLE;
3691 DirectiveKindMap[".align"] = DK_ALIGN;
3692 DirectiveKindMap[".align32"] = DK_ALIGN32;
3693 DirectiveKindMap[".balign"] = DK_BALIGN;
3694 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3695 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3696 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3697 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3698 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3699 DirectiveKindMap[".org"] = DK_ORG;
3700 DirectiveKindMap[".fill"] = DK_FILL;
3701 DirectiveKindMap[".zero"] = DK_ZERO;
3702 DirectiveKindMap[".extern"] = DK_EXTERN;
3703 DirectiveKindMap[".globl"] = DK_GLOBL;
3704 DirectiveKindMap[".global"] = DK_GLOBAL;
3705 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3706 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3707 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3708 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3709 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3710 DirectiveKindMap[".reference"] = DK_REFERENCE;
3711 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3712 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3713 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3714 DirectiveKindMap[".comm"] = DK_COMM;
3715 DirectiveKindMap[".common"] = DK_COMMON;
3716 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3717 DirectiveKindMap[".abort"] = DK_ABORT;
3718 DirectiveKindMap[".include"] = DK_INCLUDE;
3719 DirectiveKindMap[".incbin"] = DK_INCBIN;
3720 DirectiveKindMap[".code16"] = DK_CODE16;
3721 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3722 DirectiveKindMap[".rept"] = DK_REPT;
3723 DirectiveKindMap[".irp"] = DK_IRP;
3724 DirectiveKindMap[".irpc"] = DK_IRPC;
3725 DirectiveKindMap[".endr"] = DK_ENDR;
3726 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3727 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3728 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3729 DirectiveKindMap[".if"] = DK_IF;
3730 DirectiveKindMap[".ifb"] = DK_IFB;
3731 DirectiveKindMap[".ifnb"] = DK_IFNB;
3732 DirectiveKindMap[".ifc"] = DK_IFC;
3733 DirectiveKindMap[".ifnc"] = DK_IFNC;
3734 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3735 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3736 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3737 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3738 DirectiveKindMap[".else"] = DK_ELSE;
3739 DirectiveKindMap[".endif"] = DK_ENDIF;
3740 DirectiveKindMap[".skip"] = DK_SKIP;
3741 DirectiveKindMap[".space"] = DK_SPACE;
3742 DirectiveKindMap[".file"] = DK_FILE;
3743 DirectiveKindMap[".line"] = DK_LINE;
3744 DirectiveKindMap[".loc"] = DK_LOC;
3745 DirectiveKindMap[".stabs"] = DK_STABS;
3746 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3747 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3748 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3749 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3750 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3751 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3752 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3753 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3754 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3755 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3756 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3757 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3758 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3759 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3760 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3761 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3762 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3763 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3764 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3765 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3766 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3767 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3768 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3769 DirectiveKindMap[".macro"] = DK_MACRO;
3770 DirectiveKindMap[".endm"] = DK_ENDM;
3771 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3772 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003773}
3774
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003775
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003776MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003777 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003778
Rafael Espindola761cb062012-06-03 23:57:14 +00003779 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003780 for (;;) {
3781 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003782 if (getLexer().is(AsmToken::Eof)) {
3783 Error(DirectiveLoc, "no matching '.endr' in definition");
3784 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003785 }
3786
Rafael Espindola761cb062012-06-03 23:57:14 +00003787 if (Lexer.is(AsmToken::Identifier) &&
3788 (getTok().getIdentifier() == ".rept")) {
3789 ++NestLevel;
3790 }
3791
3792 // Otherwise, check whether we have reached the .endr.
3793 if (Lexer.is(AsmToken::Identifier) &&
3794 getTok().getIdentifier() == ".endr") {
3795 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003796 EndToken = getTok();
3797 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003798 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3799 TokError("unexpected token in '.endr' directive");
3800 return 0;
3801 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003802 break;
3803 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003804 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003805 }
3806
Rafael Espindola761cb062012-06-03 23:57:14 +00003807 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003808 EatToEndOfStatement();
3809 }
3810
3811 const char *BodyStart = StartToken.getLoc().getPointer();
3812 const char *BodyEnd = EndToken.getLoc().getPointer();
3813 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3814
Rafael Espindola761cb062012-06-03 23:57:14 +00003815 // We Are Anonymous.
3816 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003817 MCAsmMacroParameters Parameters;
3818 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003819}
3820
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003821void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003822 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003823 OS << ".endr\n";
3824
3825 MemoryBuffer *Instantiation =
3826 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3827
Rafael Espindola761cb062012-06-03 23:57:14 +00003828 // Create the macro instantiation object and add to the current macro
3829 // instantiation stack.
3830 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003831 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003832 getTok().getLoc(),
3833 Instantiation);
3834 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003835
Rafael Espindola761cb062012-06-03 23:57:14 +00003836 // Jump to the macro instantiation and prime the lexer.
3837 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3838 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3839 Lex();
3840}
3841
3842bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3843 int64_t Count;
3844 if (ParseAbsoluteExpression(Count))
3845 return TokError("unexpected token in '.rept' directive");
3846
3847 if (Count < 0)
3848 return TokError("Count is negative");
3849
3850 if (Lexer.isNot(AsmToken::EndOfStatement))
3851 return TokError("unexpected token in '.rept' directive");
3852
3853 // Eat the end of statement.
3854 Lex();
3855
3856 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003857 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003858 if (!M)
3859 return true;
3860
3861 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3862 // to hold the macro body with substitutions.
3863 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003864 MCAsmMacroParameters Parameters;
3865 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003866 raw_svector_ostream OS(Buf);
3867 while (Count--) {
3868 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3869 return true;
3870 }
3871 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003872
3873 return false;
3874}
3875
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003876/// ParseDirectiveIrp
3877/// ::= .irp symbol,values
3878bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003879 MCAsmMacroParameters Parameters;
3880 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003881
Preston Gurd6c9176a2012-09-19 20:29:04 +00003882 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003883 return TokError("expected identifier in '.irp' directive");
3884
3885 Parameters.push_back(Parameter);
3886
3887 if (Lexer.isNot(AsmToken::Comma))
3888 return TokError("expected comma in '.irp' directive");
3889
3890 Lex();
3891
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003892 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003893 if (ParseMacroArguments(0, A))
3894 return true;
3895
3896 // Eat the end of statement.
3897 Lex();
3898
3899 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003900 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003901 if (!M)
3902 return true;
3903
3904 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3905 // to hold the macro body with substitutions.
3906 SmallString<256> Buf;
3907 raw_svector_ostream OS(Buf);
3908
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003909 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3910 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003911 Args.push_back(*i);
3912
3913 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3914 return true;
3915 }
3916
3917 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3918
3919 return false;
3920}
3921
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003922/// ParseDirectiveIrpc
3923/// ::= .irpc symbol,values
3924bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003925 MCAsmMacroParameters Parameters;
3926 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003927
Preston Gurd6c9176a2012-09-19 20:29:04 +00003928 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003929 return TokError("expected identifier in '.irpc' directive");
3930
3931 Parameters.push_back(Parameter);
3932
3933 if (Lexer.isNot(AsmToken::Comma))
3934 return TokError("expected comma in '.irpc' directive");
3935
3936 Lex();
3937
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003938 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003939 if (ParseMacroArguments(0, A))
3940 return true;
3941
3942 if (A.size() != 1 || A.front().size() != 1)
3943 return TokError("unexpected token in '.irpc' directive");
3944
3945 // Eat the end of statement.
3946 Lex();
3947
3948 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003949 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003950 if (!M)
3951 return true;
3952
3953 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3954 // to hold the macro body with substitutions.
3955 SmallString<256> Buf;
3956 raw_svector_ostream OS(Buf);
3957
3958 StringRef Values = A.front().front().getString();
3959 std::size_t I, End = Values.size();
3960 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003961 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003962 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3963
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003964 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003965 Args.push_back(Arg);
3966
3967 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3968 return true;
3969 }
3970
3971 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3972
3973 return false;
3974}
3975
Rafael Espindola761cb062012-06-03 23:57:14 +00003976bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3977 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003978 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003979
3980 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003981 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003982 assert(getLexer().is(AsmToken::EndOfStatement));
3983
Rafael Espindola761cb062012-06-03 23:57:14 +00003984 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003985 return false;
3986}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003987
Eli Friedman2128aae2012-10-22 23:58:19 +00003988bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3989 const MCExpr *Value;
3990 SMLoc ExprLoc = getLexer().getLoc();
3991 if (ParseExpression(Value))
3992 return true;
3993 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3994 if (!MCE)
3995 return Error(ExprLoc, "unexpected expression in _emit");
3996 uint64_t IntValue = MCE->getValue();
3997 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3998 return Error(ExprLoc, "literal value out of range for directive");
3999
4000 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
4001 return false;
4002}
4003
Chad Rosierb1f8c132012-10-18 15:49:34 +00004004bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4005 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004006 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00004007 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00004008 SmallVectorImpl<std::string> &Clobbers,
4009 const MCInstrInfo *MII,
4010 const MCInstPrinter *IP,
4011 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004012 SmallVector<void *, 4> InputDecls;
4013 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004014 SmallVector<bool, 4> InputDeclsAddressOf;
4015 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004016 SmallVector<std::string, 4> InputConstraints;
4017 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004018 std::set<std::string> ClobberRegs;
4019
Chad Rosier4e472d22012-10-20 01:02:45 +00004020 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004021
4022 // Prime the lexer.
4023 Lex();
4024
4025 // While we have input, parse each statement.
4026 unsigned InputIdx = 0;
4027 unsigned OutputIdx = 0;
4028 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004029 ParseStatementInfo Info(&AsmStrRewrites);
4030 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004031 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004032
Chad Rosier57498012012-12-12 22:45:52 +00004033 if (Info.ParseError)
4034 return true;
4035
Eli Friedman2128aae2012-10-22 23:58:19 +00004036 if (Info.Opcode != ~0U) {
4037 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004038
4039 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00004040 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4041 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004042
4043 // Immediate.
4044 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00004045 if (Operand->needAsmRewrite())
4046 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
4047 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004048 continue;
4049 }
4050
4051 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00004052 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004053 unsigned NumDefs = Desc.getNumDefs();
4054 // Clobber.
4055 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
4056 std::string Reg;
4057 raw_string_ostream OS(Reg);
4058 IP->printRegName(OS, Operand->getReg());
4059 ClobberRegs.insert(StringRef(OS.str()));
4060 }
4061 continue;
4062 }
4063
4064 // Expr/Input or Output.
Chad Rosierc1ec2072013-01-10 22:10:27 +00004065 bool IsVarDecl;
Chad Rosier505bca32013-01-17 19:21:48 +00004066 unsigned Length, Size, Type;
Chad Rosier32989592012-10-18 20:27:15 +00004067 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosier505bca32013-01-17 19:21:48 +00004068 Length, Size, Type, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004069 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004070 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00004071 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00004072 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00004073 Operand->getStartLoc(),
4074 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004075 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004076 if (isOutput) {
4077 std::string Constraint = "=";
4078 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004079 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00004080 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00004081 Constraint += Operand->getConstraint().str();
4082 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00004083 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004084 Operand->getStartLoc(),
4085 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004086 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004087 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00004088 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00004089 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00004090 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004091 Operand->getStartLoc(),
4092 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004093 }
4094 }
4095 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004096 }
4097 }
4098
4099 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004100 NumOutputs = OutputDecls.size();
4101 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004102
4103 // Set the unique clobbers.
4104 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4105 E = ClobberRegs.end(); I != E; ++I)
4106 Clobbers.push_back(*I);
4107
4108 // Merge the various outputs and inputs. Output are expected first.
4109 if (NumOutputs || NumInputs) {
4110 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004111 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004112 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004113 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004114 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004115 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004116 }
4117 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004118 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004119 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004120 }
4121 }
4122
4123 // Build the IR assembly string.
4124 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004125 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004126 raw_string_ostream OS(AsmStringIR);
4127 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00004128 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004129 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4130 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004131
Chad Rosier4e472d22012-10-20 01:02:45 +00004132 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004133
4134 // Emit everything up to the immediate/expression. If the previous rewrite
4135 // was a size directive, then this has already been done.
4136 if (PrevKind != AOK_SizeDirective)
4137 OS << StringRef(Start, Loc - Start);
4138 PrevKind = Kind;
4139
Chad Rosier5a719fc2012-10-23 17:43:43 +00004140 // Skip the original expression.
4141 if (Kind == AOK_Skip) {
4142 Start = Loc + (*I).Len;
4143 continue;
4144 }
4145
Chad Rosierb1f8c132012-10-18 15:49:34 +00004146 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004147 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004148 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004149 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004150 OS << Twine("$$");
4151 OS << (*I).Val;
4152 break;
4153 case AOK_ImmPrefix:
4154 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004155 break;
4156 case AOK_Input:
4157 OS << '$';
4158 OS << InputIdx++;
4159 break;
4160 case AOK_Output:
4161 OS << '$';
4162 OS << OutputIdx++;
4163 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004164 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004165 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004166 default: break;
4167 case 8: OS << "byte ptr "; break;
4168 case 16: OS << "word ptr "; break;
4169 case 32: OS << "dword ptr "; break;
4170 case 64: OS << "qword ptr "; break;
4171 case 80: OS << "xword ptr "; break;
4172 case 128: OS << "xmmword ptr "; break;
4173 case 256: OS << "ymmword ptr "; break;
4174 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004175 break;
4176 case AOK_Emit:
4177 OS << ".byte";
4178 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004179 case AOK_DotOperator:
4180 OS << (*I).Val;
4181 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004182 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004183
Chad Rosierb1f8c132012-10-18 15:49:34 +00004184 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004185 if (Kind != AOK_SizeDirective)
4186 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004187 }
4188
4189 // Emit the remainder of the asm string.
4190 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4191 if (Start != AsmEnd)
4192 OS << StringRef(Start, AsmEnd - Start);
4193
4194 AsmString = OS.str();
4195 return false;
4196}
4197
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004198/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004199MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004200 MCContext &C, MCStreamer &Out,
4201 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004202 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004203}