blob: 0644ea341a3b040298dd49d48b734f8dcd6d181c [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
Chad Rosier469b1442013-02-12 21:33:51 +0000446 // "_emit" or "__emit"
447 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
448 size_t Len);
449
450 // "align"
451 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000452
Eli Bendersky6ee13082013-01-15 22:59:42 +0000453 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000454};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000455}
456
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000457namespace llvm {
458
459extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000460extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000461extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000462
463}
464
Chris Lattneraaec2052010-01-19 19:46:13 +0000465enum { DEFAULT_ADDRSPACE = 0 };
466
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000467AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000468 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000469 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000470 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000471 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000472 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000473 // Save the old handler.
474 SavedDiagHandler = SrcMgr.getDiagHandler();
475 SavedDiagContext = SrcMgr.getDiagContext();
476 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000477 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000478 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000479
Daniel Dunbare4749702010-07-12 18:12:02 +0000480 // Initialize the platform / file format parser.
481 //
482 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
483 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000484 if (_MAI.hasMicrosoftFastStdCallMangling()) {
485 PlatformParser = createCOFFAsmParser();
486 PlatformParser->Initialize(*this);
487 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000488 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000489 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000490 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000491 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000492 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000493 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000494 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000495
Eli Bendersky6ee13082013-01-15 22:59:42 +0000496 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000497}
498
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000499AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000500 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
501
502 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000503 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000504 ie = MacroMap.end(); it != ie; ++it)
505 delete it->getValue();
506
Daniel Dunbare4749702010-07-12 18:12:02 +0000507 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000508}
509
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000510void AsmParser::PrintMacroInstantiations() {
511 // Print the active macro instantiation stack.
512 for (std::vector<MacroInstantiation*>::const_reverse_iterator
513 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000514 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
515 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000516}
517
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000518bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000519 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000520 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000521 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000522 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000523 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000524}
525
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000526bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000527 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000528 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000529 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000530 return true;
531}
532
Sean Callananfd0b0282010-01-21 00:19:58 +0000533bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000534 std::string IncludedFile;
535 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000536 if (NewBuf == -1)
537 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000538
Sean Callananfd0b0282010-01-21 00:19:58 +0000539 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 return false;
544}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000545
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000546/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000547/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000548/// returns true on failure.
549bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
550 std::string IncludedFile;
551 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
552 if (NewBuf == -1)
553 return true;
554
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000555 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000556 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
557 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000558 return false;
559}
560
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000561void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
562 if (InBuffer != -1) {
563 CurBuffer = InBuffer;
564 } else {
565 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
566 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000567 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
568}
569
Sean Callananfd0b0282010-01-21 00:19:58 +0000570const AsmToken &AsmParser::Lex() {
571 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000572
Sean Callananfd0b0282010-01-21 00:19:58 +0000573 if (tok->is(AsmToken::Eof)) {
574 // If this is the end of an included file, pop the parent file off the
575 // include stack.
576 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
577 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000578 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000579 tok = &Lexer.Lex();
580 }
581 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000582
Sean Callananfd0b0282010-01-21 00:19:58 +0000583 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000584 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000585
Sean Callananfd0b0282010-01-21 00:19:58 +0000586 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000587}
588
Chris Lattner79180e22010-04-05 23:15:42 +0000589bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000590 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000591 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000592 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000593
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000594 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000595 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000596
597 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000598 AsmCond StartingCondState = TheCondState;
599
Kevin Enderby613b7572011-11-01 22:27:22 +0000600 // If we are generating dwarf for assembly source files save the initial text
601 // section and generate a .file directive.
602 if (getContext().getGenDwarfForAssembly()) {
603 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000604 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
605 getStreamer().EmitLabel(SectionStartSym);
606 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000607 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000608 StringRef(),
609 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000610 }
611
Chris Lattnerb717fb02009-07-02 21:53:43 +0000612 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000613 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000614 ParseStatementInfo Info;
615 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000616
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000617 // We had an error, validate that one was emitted and recover by skipping to
618 // the next line.
619 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000620 EatToEndOfStatement();
621 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000622
623 if (TheCondState.TheCond != StartingCondState.TheCond ||
624 TheCondState.Ignore != StartingCondState.Ignore)
625 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000626
627 // Check to see there are no empty DwarfFile slots.
628 const std::vector<MCDwarfFile *> &MCDwarfFiles =
629 getContext().getMCDwarfFiles();
630 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000631 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000632 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000633 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000634
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000635 // Check to see that all assembler local symbols were actually defined.
636 // Targets that don't do subsections via symbols may not want this, though,
637 // so conservatively exclude them. Only do this if we're finalizing, though,
638 // as otherwise we won't necessarilly have seen everything yet.
639 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
640 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
641 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
642 e = Symbols.end();
643 i != e; ++i) {
644 MCSymbol *Sym = i->getValue();
645 // Variable symbols may not be marked as defined, so check those
646 // explicitly. If we know it's a variable, we have a definition for
647 // the purposes of this check.
648 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
649 // FIXME: We would really like to refer back to where the symbol was
650 // first referenced for a source location. We need to add something
651 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000652 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
653 "assembler local symbol '" + Sym->getName() +
654 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000655 }
656 }
657
658
Chris Lattner79180e22010-04-05 23:15:42 +0000659 // Finalize the output stream if there are no errors and if the client wants
660 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000661 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000662 Out.Finish();
663
Chris Lattnerb717fb02009-07-02 21:53:43 +0000664 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000665}
666
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000667void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000668 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000669 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000670 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000671 }
672}
673
Chris Lattner2cf5f142009-06-22 01:29:09 +0000674/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
675void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000676 while (Lexer.isNot(AsmToken::EndOfStatement) &&
677 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000678 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000679
Chris Lattner2cf5f142009-06-22 01:29:09 +0000680 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000681 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000682 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000683}
684
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000685StringRef AsmParser::ParseStringToEndOfStatement() {
686 const char *Start = getTok().getLoc().getPointer();
687
688 while (Lexer.isNot(AsmToken::EndOfStatement) &&
689 Lexer.isNot(AsmToken::Eof))
690 Lex();
691
692 const char *End = getTok().getLoc().getPointer();
693 return StringRef(Start, End - Start);
694}
Chris Lattnerc4193832009-06-22 05:51:26 +0000695
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000696StringRef AsmParser::ParseStringToComma() {
697 const char *Start = getTok().getLoc().getPointer();
698
699 while (Lexer.isNot(AsmToken::EndOfStatement) &&
700 Lexer.isNot(AsmToken::Comma) &&
701 Lexer.isNot(AsmToken::Eof))
702 Lex();
703
704 const char *End = getTok().getLoc().getPointer();
705 return StringRef(Start, End - Start);
706}
707
Chris Lattner74ec1a32009-06-22 06:32:03 +0000708/// ParseParenExpr - Parse a paren expression and return it.
709/// NOTE: This assumes the leading '(' has already been consumed.
710///
711/// parenexpr ::= expr)
712///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000713bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000714 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000715 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000716 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000717 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000718 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000719 return false;
720}
Chris Lattnerc4193832009-06-22 05:51:26 +0000721
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000722/// ParseBracketExpr - Parse a bracket expression and return it.
723/// NOTE: This assumes the leading '[' has already been consumed.
724///
725/// bracketexpr ::= expr]
726///
727bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
728 if (ParseExpression(Res)) return true;
729 if (Lexer.isNot(AsmToken::RBrac))
730 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000731 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000732 Lex();
733 return false;
734}
735
Chris Lattner74ec1a32009-06-22 06:32:03 +0000736/// ParsePrimaryExpr - Parse a primary expression and return it.
737/// primaryexpr ::= (parenexpr
738/// primaryexpr ::= symbol
739/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000740/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000741/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000742bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000743 SMLoc FirstTokenLoc = getLexer().getLoc();
744 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
745 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000746 default:
747 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000748 // If we have an error assume that we've already handled it.
749 case AsmToken::Error:
750 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000751 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000752 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000753 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000754 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000755 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000756 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000757 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000758 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000759 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000760 StringRef Identifier;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000761 if (ParseIdentifier(Identifier)) {
762 if (FirstTokenKind == AsmToken::Dollar)
763 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000764 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000765 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000766
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000767 EndLoc = SMLoc::getFromPointer(Identifier.end());
768
Daniel Dunbarfffff912009-10-16 01:34:54 +0000769 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000770 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000771 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000772
773 // Lookup the symbol variant if used.
774 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000775 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000776 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000777 if (Variant == MCSymbolRefExpr::VK_Invalid) {
778 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000779 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000780 }
781 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000782
Daniel Dunbarfffff912009-10-16 01:34:54 +0000783 // If this is an absolute variable reference, substitute it now to preserve
784 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000785 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000786 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000787 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000788
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000789 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000790 return false;
791 }
792
793 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000794 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000795 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000796 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000797 case AsmToken::Integer: {
798 SMLoc Loc = getTok().getLoc();
799 int64_t IntVal = getTok().getIntVal();
800 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000801 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000802 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000803 // Look for 'b' or 'f' following an Integer as a directional label
804 if (Lexer.getKind() == AsmToken::Identifier) {
805 StringRef IDVal = getTok().getString();
806 if (IDVal == "f" || IDVal == "b"){
807 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
808 IDVal == "f" ? 1 : 0);
809 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
810 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000811 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000812 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000813 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000814 Lex(); // Eat identifier.
815 }
816 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000817 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000818 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000819 case AsmToken::Real: {
820 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000821 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000822 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000823 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000824 Lex(); // Eat token.
825 return false;
826 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000827 case AsmToken::Dot: {
828 // This is a '.' reference, which references the current PC. Emit a
829 // temporary label to the streamer and refer to it.
830 MCSymbol *Sym = Ctx.CreateTempSymbol();
831 Out.EmitLabel(Sym);
832 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000833 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000834 Lex(); // Eat identifier.
835 return false;
836 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000837 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000838 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000839 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000840 case AsmToken::LBrac:
841 if (!PlatformParser->HasBracketExpressions())
842 return TokError("brackets expression not supported on this target");
843 Lex(); // Eat the '['.
844 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000845 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000846 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000847 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000848 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000849 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000851 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000852 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000853 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000854 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000855 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000857 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000858 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000859 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000860 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000861 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000863 }
864}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000865
Chris Lattnerb4307b32010-01-15 19:28:38 +0000866bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000867 SMLoc EndLoc;
868 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000869}
870
Daniel Dunbarcceba832010-09-17 02:47:07 +0000871const MCExpr *
872AsmParser::ApplyModifierToExpr(const MCExpr *E,
873 MCSymbolRefExpr::VariantKind Variant) {
874 // Recurse over the given expression, rebuilding it to apply the given variant
875 // if there is exactly one symbol.
876 switch (E->getKind()) {
877 case MCExpr::Target:
878 case MCExpr::Constant:
879 return 0;
880
881 case MCExpr::SymbolRef: {
882 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
883
884 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
885 TokError("invalid variant on expression '" +
886 getTok().getIdentifier() + "' (already modified)");
887 return E;
888 }
889
890 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
891 }
892
893 case MCExpr::Unary: {
894 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
895 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
896 if (!Sub)
897 return 0;
898 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
899 }
900
901 case MCExpr::Binary: {
902 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
903 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
904 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
905
906 if (!LHS && !RHS)
907 return 0;
908
909 if (!LHS) LHS = BE->getLHS();
910 if (!RHS) RHS = BE->getRHS();
911
912 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
913 }
914 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000915
Craig Topper85814382012-02-07 05:05:23 +0000916 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000917}
918
Chris Lattner74ec1a32009-06-22 06:32:03 +0000919/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000920///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000921/// expr ::= expr &&,|| expr -> lowest.
922/// expr ::= expr |,^,&,! expr
923/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
924/// expr ::= expr <<,>> expr
925/// expr ::= expr +,- expr
926/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000927/// expr ::= primaryexpr
928///
Chris Lattner54482b42010-01-15 19:39:23 +0000929bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000930 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000931 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000932 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
933 return true;
934
Daniel Dunbarcceba832010-09-17 02:47:07 +0000935 // As a special case, we support 'a op b @ modifier' by rewriting the
936 // expression to include the modifier. This is inefficient, but in general we
937 // expect users to use 'a@modifier op b'.
938 if (Lexer.getKind() == AsmToken::At) {
939 Lex();
940
941 if (Lexer.isNot(AsmToken::Identifier))
942 return TokError("unexpected symbol modifier following '@'");
943
944 MCSymbolRefExpr::VariantKind Variant =
945 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
946 if (Variant == MCSymbolRefExpr::VK_Invalid)
947 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
948
949 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
950 if (!ModifiedRes) {
951 return TokError("invalid modifier '" + getTok().getIdentifier() +
952 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000953 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000954
Daniel Dunbarcceba832010-09-17 02:47:07 +0000955 Res = ModifiedRes;
956 Lex();
957 }
958
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000959 // Try to constant fold it up front, if possible.
960 int64_t Value;
961 if (Res->EvaluateAsAbsolute(Value))
962 Res = MCConstantExpr::Create(Value, getContext());
963
964 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000965}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000966
Chris Lattnerb4307b32010-01-15 19:28:38 +0000967bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000968 Res = 0;
969 return ParseParenExpr(Res, EndLoc) ||
970 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000971}
972
Daniel Dunbar475839e2009-06-29 20:37:27 +0000973bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000974 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000975
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000976 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000977 if (ParseExpression(Expr))
978 return true;
979
Daniel Dunbare00b0112009-10-16 01:57:52 +0000980 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000981 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000982
983 return false;
984}
985
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000986static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000987 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000988 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000989 default:
990 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000991
Jim Grosbachfbe16812011-08-20 16:24:13 +0000992 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000993 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000994 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000995 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000996 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000997 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000998 return 1;
999
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001000
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001001 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001002 //
1003 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001004 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001005 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001006 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001007 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001008 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001009 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001012 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001013
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001014 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001015 case AsmToken::EqualEqual:
1016 Kind = MCBinaryExpr::EQ;
1017 return 3;
1018 case AsmToken::ExclaimEqual:
1019 case AsmToken::LessGreater:
1020 Kind = MCBinaryExpr::NE;
1021 return 3;
1022 case AsmToken::Less:
1023 Kind = MCBinaryExpr::LT;
1024 return 3;
1025 case AsmToken::LessEqual:
1026 Kind = MCBinaryExpr::LTE;
1027 return 3;
1028 case AsmToken::Greater:
1029 Kind = MCBinaryExpr::GT;
1030 return 3;
1031 case AsmToken::GreaterEqual:
1032 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001033 return 3;
1034
Jim Grosbachfbe16812011-08-20 16:24:13 +00001035 // Intermediate Precedence: <<, >>
1036 case AsmToken::LessLess:
1037 Kind = MCBinaryExpr::Shl;
1038 return 4;
1039 case AsmToken::GreaterGreater:
1040 Kind = MCBinaryExpr::Shr;
1041 return 4;
1042
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001043 // High Intermediate Precedence: +, -
1044 case AsmToken::Plus:
1045 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001046 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001047 case AsmToken::Minus:
1048 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001049 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001050
Jim Grosbachfbe16812011-08-20 16:24:13 +00001051 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001052 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001053 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001054 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001055 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001056 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001058 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001059 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001060 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001061 }
1062}
1063
1064
1065/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1066/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001067bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1068 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001069 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001070 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001071 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001072
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001073 // If the next token is lower precedence than we are allowed to eat, return
1074 // successfully with what we ate already.
1075 if (TokPrec < Precedence)
1076 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001077
Sean Callanan79ed1a82010-01-19 20:22:31 +00001078 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001079
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001080 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001081 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001082 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001083
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 // If BinOp binds less tightly with RHS than the operator after RHS, let
1085 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001086 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001087 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001088 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001089 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001090 }
1091
Daniel Dunbar475839e2009-06-29 20:37:27 +00001092 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001093 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001094 }
1095}
1096
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001097/// ParseStatement:
1098/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001099/// ::= Label* Directive ...Operands... EndOfStatement
1100/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001101bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001102 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001103 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001104 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001105 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001106 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001107
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001108 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001109 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001110 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001111 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001112 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001113 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001114 if (Lexer.is(AsmToken::Hash))
1115 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001116
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001117 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001118 if (Lexer.is(AsmToken::Integer)) {
1119 LocalLabelVal = getTok().getIntVal();
1120 if (LocalLabelVal < 0) {
1121 if (!TheCondState.Ignore)
1122 return TokError("unexpected token at start of statement");
1123 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001124 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001125 IDVal = getTok().getString();
1126 Lex(); // Consume the integer token to be used as an identifier token.
1127 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001128 if (!TheCondState.Ignore)
1129 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001130 }
1131 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001132 } else if (Lexer.is(AsmToken::Dot)) {
1133 // Treat '.' as a valid identifier in this context.
1134 Lex();
1135 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001136 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001137 if (!TheCondState.Ignore)
1138 return TokError("unexpected token at start of statement");
1139 IDVal = "";
1140 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001141
Chris Lattner7834fac2010-04-17 18:14:27 +00001142 // Handle conditional assembly here before checking for skipping. We
1143 // have to do this so that .endif isn't skipped in a ".if 0" block for
1144 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001145 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001146 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001147 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001148 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1149 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001150 switch (DirKind) {
1151 default:
1152 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001153 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001154 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001155 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001157 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001158 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001159 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001160 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001161 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001162 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001163 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001164 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001165 case DK_IFNDEF:
1166 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001167 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001168 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001169 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001170 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001171 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001172 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001173 return ParseDirectiveEndIf(IDLoc);
1174 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001175
Eli Benderskyed5df012013-01-16 19:32:36 +00001176 // Ignore the statement if in the middle of inactive conditional
1177 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001178 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001179 EatToEndOfStatement();
1180 return false;
1181 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001182
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001183 // FIXME: Recurse on local labels?
1184
1185 // See what kind of statement we have.
1186 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001187 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001188 CheckForValidSection();
1189
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001190 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001191 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001192
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001193 // Diagnose attempt to use '.' as a label.
1194 if (IDVal == ".")
1195 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1196
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001197 // Diagnose attempt to use a variable as a label.
1198 //
1199 // FIXME: Diagnostics. Note the location of the definition as a label.
1200 // FIXME: This doesn't diagnose assignment to a symbol which has been
1201 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001202 MCSymbol *Sym;
1203 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001204 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001205 else
1206 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001207 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001208 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001209
Daniel Dunbar959fd882009-08-26 22:13:22 +00001210 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001211 if (!ParsingInlineAsm)
1212 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001213
Kevin Enderby94c2e852011-12-09 18:09:40 +00001214 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001215 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001216 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001217 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1218 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001219
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001220 // Consume any end of statement token, if present, to avoid spurious
1221 // AddBlankLine calls().
1222 if (Lexer.is(AsmToken::EndOfStatement)) {
1223 Lex();
1224 if (Lexer.is(AsmToken::Eof))
1225 return false;
1226 }
1227
Eli Friedman2128aae2012-10-22 23:58:19 +00001228 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001229 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001230
Daniel Dunbar3f872332009-07-28 16:08:33 +00001231 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001232 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001233 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001234
Nico Weber4c4c7322011-01-28 03:04:41 +00001235 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001236
1237 default: // Normal instruction or directive.
1238 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001239 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001240
1241 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001242 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001243 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1244 return HandleMacroEntry(M, IDLoc);
1245 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001246
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001247 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001248
1249 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001250 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001251 // There are several entities interested in parsing directives:
1252 //
1253 // 1. The target-specific assembly parser. Some directives are target
1254 // specific or may potentially behave differently on certain targets.
1255 // 2. Asm parser extensions. For example, platform-specific parsers
1256 // (like the ELF parser) register themselves as extensions.
1257 // 3. The generic directive parser implemented by this class. These are
1258 // all the directives that behave in a target and platform independent
1259 // manner, or at least have a default behavior that's shared between
1260 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001261
Eli Bendersky6ee13082013-01-15 22:59:42 +00001262 // First query the target-specific parser. It will return 'true' if it
1263 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001264 if (!getTargetParser().ParseDirective(ID))
1265 return false;
1266
Eli Bendersky6ee13082013-01-15 22:59:42 +00001267 // Next, check the extention directive map to see if any extension has
1268 // registered itself to parse this directive.
1269 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1270 ExtensionDirectiveMap.lookup(IDVal);
1271 if (Handler.first)
1272 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1273
1274 // Finally, if no one else is interested in this directive, it must be
1275 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001276 switch (DirKind) {
1277 default:
1278 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001279 case DK_SET:
1280 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001281 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001282 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001283 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001284 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001285 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001286 case DK_ASCIZ:
1287 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001288 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001289 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001290 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001291 case DK_SHORT:
1292 case DK_VALUE:
1293 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001294 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001295 case DK_LONG:
1296 case DK_INT:
1297 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001299 case DK_QUAD:
1300 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001301 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001302 case DK_SINGLE:
1303 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001308 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1309 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1310 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1313 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1314 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001319 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001329 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 EatToEndOfStatement(); // .extern is the default, ignore it.
1335 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001336 case DK_GLOBL:
1337 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001352 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001353 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001354 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001355 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001356 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001357 case DK_COMM:
1358 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001363 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001364 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001365 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001366 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_CODE16:
1369 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001374 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001375 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001379 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001380 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001381 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001382 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001383 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001384 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001385 case DK_SLEB128:
1386 return ParseDirectiveLEB128(true);
1387 case DK_ULEB128:
1388 return ParseDirectiveLEB128(false);
1389 case DK_SPACE:
1390 case DK_SKIP:
1391 return ParseDirectiveSpace(IDVal);
1392 case DK_FILE:
1393 return ParseDirectiveFile(IDLoc);
1394 case DK_LINE:
1395 return ParseDirectiveLine();
1396 case DK_LOC:
1397 return ParseDirectiveLoc();
1398 case DK_STABS:
1399 return ParseDirectiveStabs();
1400 case DK_CFI_SECTIONS:
1401 return ParseDirectiveCFISections();
1402 case DK_CFI_STARTPROC:
1403 return ParseDirectiveCFIStartProc();
1404 case DK_CFI_ENDPROC:
1405 return ParseDirectiveCFIEndProc();
1406 case DK_CFI_DEF_CFA:
1407 return ParseDirectiveCFIDefCfa(IDLoc);
1408 case DK_CFI_DEF_CFA_OFFSET:
1409 return ParseDirectiveCFIDefCfaOffset();
1410 case DK_CFI_ADJUST_CFA_OFFSET:
1411 return ParseDirectiveCFIAdjustCfaOffset();
1412 case DK_CFI_DEF_CFA_REGISTER:
1413 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1414 case DK_CFI_OFFSET:
1415 return ParseDirectiveCFIOffset(IDLoc);
1416 case DK_CFI_REL_OFFSET:
1417 return ParseDirectiveCFIRelOffset(IDLoc);
1418 case DK_CFI_PERSONALITY:
1419 return ParseDirectiveCFIPersonalityOrLsda(true);
1420 case DK_CFI_LSDA:
1421 return ParseDirectiveCFIPersonalityOrLsda(false);
1422 case DK_CFI_REMEMBER_STATE:
1423 return ParseDirectiveCFIRememberState();
1424 case DK_CFI_RESTORE_STATE:
1425 return ParseDirectiveCFIRestoreState();
1426 case DK_CFI_SAME_VALUE:
1427 return ParseDirectiveCFISameValue(IDLoc);
1428 case DK_CFI_RESTORE:
1429 return ParseDirectiveCFIRestore(IDLoc);
1430 case DK_CFI_ESCAPE:
1431 return ParseDirectiveCFIEscape();
1432 case DK_CFI_SIGNAL_FRAME:
1433 return ParseDirectiveCFISignalFrame();
1434 case DK_CFI_UNDEFINED:
1435 return ParseDirectiveCFIUndefined(IDLoc);
1436 case DK_CFI_REGISTER:
1437 return ParseDirectiveCFIRegister(IDLoc);
1438 case DK_MACROS_ON:
1439 case DK_MACROS_OFF:
1440 return ParseDirectiveMacrosOnOff(IDVal);
1441 case DK_MACRO:
1442 return ParseDirectiveMacro(IDLoc);
1443 case DK_ENDM:
1444 case DK_ENDMACRO:
1445 return ParseDirectiveEndMacro(IDVal);
1446 case DK_PURGEM:
1447 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001448 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001449
Jim Grosbach686c0182012-05-01 18:38:27 +00001450 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001451 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001452
Chad Rosier469b1442013-02-12 21:33:51 +00001453 // __asm _emit or __asm __emit
1454 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1455 IDVal == "_EMIT" || IDVal == "__EMIT"))
1456 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1457
1458 // __asm align
1459 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1460 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001461
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001462 CheckForValidSection();
1463
Chris Lattnera7f13542010-05-19 23:34:33 +00001464 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001465 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001466 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001467 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1468 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001469 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001470
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001471 // Dump the parsed representation, if requested.
1472 if (getShowParsedOperands()) {
1473 SmallString<256> Str;
1474 raw_svector_ostream OS(Str);
1475 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001476 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001477 if (i != 0)
1478 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001479 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001480 }
1481 OS << "]";
1482
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001483 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001484 }
1485
Kevin Enderby613b7572011-11-01 22:27:22 +00001486 // If we are generating dwarf for assembly source files and the current
1487 // section is the initial text section then generate a .loc directive for
1488 // the instruction.
1489 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001490 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001491
Eli Benderskyed5df012013-01-16 19:32:36 +00001492 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001493
Eli Benderskyed5df012013-01-16 19:32:36 +00001494 // If we previously parsed a cpp hash file line comment then make sure the
1495 // current Dwarf File is for the CppHashFilename if not then emit the
1496 // Dwarf File table for it and adjust the line number for the .loc.
1497 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1498 getContext().getMCDwarfFiles();
1499 if (CppHashFilename.size() != 0) {
1500 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001501 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001502 getStreamer().EmitDwarfFileDirective(
1503 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001504
Kevin Enderby32c1a822012-11-05 21:55:41 +00001505 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001506 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001507 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001508
Kevin Enderby613b7572011-11-01 22:27:22 +00001509 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001510 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001511 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001512 StringRef());
1513 }
1514
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001515 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001516 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001517 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001518 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1519 Info.ParsedOperands,
1520 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001521 ParsingInlineAsm);
1522 }
Chris Lattner98986712010-01-14 22:21:20 +00001523
Chris Lattnercbf8a982010-09-11 16:18:25 +00001524 // Don't skip the rest of the line, the instruction parser is responsible for
1525 // that.
1526 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001527}
Chris Lattner9a023f72009-06-24 04:43:34 +00001528
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001529/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1530/// since they may not be able to be tokenized to get to the end of line token.
1531void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001532 if (!Lexer.is(AsmToken::EndOfStatement))
1533 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001534 // Eat EOL.
1535 Lex();
1536}
1537
1538/// ParseCppHashLineFilenameComment as this:
1539/// ::= # number "filename"
1540/// or just as a full line comment if it doesn't have a number and a string.
1541bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1542 Lex(); // Eat the hash token.
1543
1544 if (getLexer().isNot(AsmToken::Integer)) {
1545 // Consume the line since in cases it is not a well-formed line directive,
1546 // as if were simply a full line comment.
1547 EatToEndOfLine();
1548 return false;
1549 }
1550
1551 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001552 Lex();
1553
1554 if (getLexer().isNot(AsmToken::String)) {
1555 EatToEndOfLine();
1556 return false;
1557 }
1558
1559 StringRef Filename = getTok().getString();
1560 // Get rid of the enclosing quotes.
1561 Filename = Filename.substr(1, Filename.size()-2);
1562
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001563 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1564 CppHashLoc = L;
1565 CppHashFilename = Filename;
1566 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001567 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001568
1569 // Ignore any trailing characters, they're just comment.
1570 EatToEndOfLine();
1571 return false;
1572}
1573
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001574/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001575/// for the Filename and LineNo if any in the diagnostic.
1576void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1577 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1578 raw_ostream &OS = errs();
1579
1580 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1581 const SMLoc &DiagLoc = Diag.getLoc();
1582 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1583 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1584
1585 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1586 // before printing the message.
1587 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001588 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001589 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1590 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1591 }
1592
Eric Christopher2318ba12012-12-18 00:30:54 +00001593 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001594 // manager changed or buffer changed (like in a nested include) then just
1595 // print the normal diagnostic using its Filename and LineNo.
1596 if (!Parser->CppHashLineNumber ||
1597 &DiagSrcMgr != &Parser->SrcMgr ||
1598 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001599 if (Parser->SavedDiagHandler)
1600 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1601 else
1602 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001603 return;
1604 }
1605
Eric Christopher2318ba12012-12-18 00:30:54 +00001606 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001607 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1608 // the diagnostic.
1609 const std::string Filename = Parser->CppHashFilename;
1610
1611 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1612 int CppHashLocLineNo =
1613 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1614 int LineNo = Parser->CppHashLineNumber - 1 +
1615 (DiagLocLineNo - CppHashLocLineNo);
1616
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001617 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1618 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001619 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001620 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001621
Benjamin Kramer04a04262011-10-16 10:48:29 +00001622 if (Parser->SavedDiagHandler)
1623 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1624 else
1625 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001626}
1627
Rafael Espindola799aacf2012-08-21 18:29:30 +00001628// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1629// difference being that that function accepts '@' as part of identifiers and
1630// we can't do that. AsmLexer.cpp should probably be changed to handle
1631// '@' as a special case when needed.
1632static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001633 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1634 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001635}
1636
Rafael Espindola761cb062012-06-03 23:57:14 +00001637bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001638 const MCAsmMacroParameters &Parameters,
1639 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001640 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001641 unsigned NParameters = Parameters.size();
1642 if (NParameters != 0 && NParameters != A.size())
1643 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001644
Preston Gurd7b6f2032012-09-19 20:36:12 +00001645 // A macro without parameters is handled differently on Darwin:
1646 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001647 while (!Body.empty()) {
1648 // Scan for the next substitution.
1649 std::size_t End = Body.size(), Pos = 0;
1650 for (; Pos != End; ++Pos) {
1651 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001652 if (!NParameters) {
1653 // This macro has no parameters, look for $0, $1, etc.
1654 if (Body[Pos] != '$' || Pos + 1 == End)
1655 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001656
Rafael Espindola65366442011-06-05 02:43:45 +00001657 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001658 if (Next == '$' || Next == 'n' ||
1659 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001660 break;
1661 } else {
1662 // This macro has parameters, look for \foo, \bar, etc.
1663 if (Body[Pos] == '\\' && Pos + 1 != End)
1664 break;
1665 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001666 }
1667
1668 // Add the prefix.
1669 OS << Body.slice(0, Pos);
1670
1671 // Check if we reached the end.
1672 if (Pos == End)
1673 break;
1674
Rafael Espindola65366442011-06-05 02:43:45 +00001675 if (!NParameters) {
1676 switch (Body[Pos+1]) {
1677 // $$ => $
1678 case '$':
1679 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001680 break;
1681
Rafael Espindola65366442011-06-05 02:43:45 +00001682 // $n => number of arguments
1683 case 'n':
1684 OS << A.size();
1685 break;
1686
1687 // $[0-9] => argument
1688 default: {
1689 // Missing arguments are ignored.
1690 unsigned Index = Body[Pos+1] - '0';
1691 if (Index >= A.size())
1692 break;
1693
1694 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001695 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001696 ie = A[Index].end(); it != ie; ++it)
1697 OS << it->getString();
1698 break;
1699 }
1700 }
1701 Pos += 2;
1702 } else {
1703 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001704 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001705 ++I;
1706
1707 const char *Begin = Body.data() + Pos +1;
1708 StringRef Argument(Begin, I - (Pos +1));
1709 unsigned Index = 0;
1710 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001711 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001712 break;
1713
Preston Gurd7b6f2032012-09-19 20:36:12 +00001714 if (Index == NParameters) {
1715 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1716 Pos += 3;
1717 else {
1718 OS << '\\' << Argument;
1719 Pos = I;
1720 }
1721 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001722 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001723 ie = A[Index].end(); it != ie; ++it)
1724 if (it->getKind() == AsmToken::String)
1725 OS << it->getStringContents();
1726 else
1727 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001728
Preston Gurd7b6f2032012-09-19 20:36:12 +00001729 Pos += 1 + Argument.size();
1730 }
Rafael Espindola65366442011-06-05 02:43:45 +00001731 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001732 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001733 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001734 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001735
Rafael Espindola65366442011-06-05 02:43:45 +00001736 return false;
1737}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001738
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001739MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001740 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001741 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001742 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1743 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001744{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001745}
1746
Preston Gurd7b6f2032012-09-19 20:36:12 +00001747static bool IsOperator(AsmToken::TokenKind kind)
1748{
1749 switch (kind)
1750 {
1751 default:
1752 return false;
1753 case AsmToken::Plus:
1754 case AsmToken::Minus:
1755 case AsmToken::Tilde:
1756 case AsmToken::Slash:
1757 case AsmToken::Star:
1758 case AsmToken::Dot:
1759 case AsmToken::Equal:
1760 case AsmToken::EqualEqual:
1761 case AsmToken::Pipe:
1762 case AsmToken::PipePipe:
1763 case AsmToken::Caret:
1764 case AsmToken::Amp:
1765 case AsmToken::AmpAmp:
1766 case AsmToken::Exclaim:
1767 case AsmToken::ExclaimEqual:
1768 case AsmToken::Percent:
1769 case AsmToken::Less:
1770 case AsmToken::LessEqual:
1771 case AsmToken::LessLess:
1772 case AsmToken::LessGreater:
1773 case AsmToken::Greater:
1774 case AsmToken::GreaterEqual:
1775 case AsmToken::GreaterGreater:
1776 return true;
1777 }
1778}
1779
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001780bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001781 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001782 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001783 unsigned AddTokens = 0;
1784
1785 // gas accepts arguments separated by whitespace, except on Darwin
1786 if (!IsDarwin)
1787 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001788
1789 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001790 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1791 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001792 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001793 }
1794
1795 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1796 // Spaces and commas cannot be mixed to delimit parameters
1797 if (ArgumentDelimiter == AsmToken::Eof)
1798 ArgumentDelimiter = AsmToken::Comma;
1799 else if (ArgumentDelimiter != AsmToken::Comma) {
1800 Lexer.setSkipSpace(true);
1801 return TokError("expected ' ' for macro argument separator");
1802 }
1803 break;
1804 }
1805
1806 if (Lexer.is(AsmToken::Space)) {
1807 Lex(); // Eat spaces
1808
1809 // Spaces can delimit parameters, but could also be part an expression.
1810 // If the token after a space is an operator, add the token and the next
1811 // one into this argument
1812 if (ArgumentDelimiter == AsmToken::Space ||
1813 ArgumentDelimiter == AsmToken::Eof) {
1814 if (IsOperator(Lexer.getKind())) {
1815 // Check to see whether the token is used as an operator,
1816 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001817 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001818 if (*NextChar == ' ')
1819 AddTokens = 2;
1820 }
1821
1822 if (!AddTokens && ParenLevel == 0) {
1823 if (ArgumentDelimiter == AsmToken::Eof &&
1824 !IsOperator(Lexer.getKind()))
1825 ArgumentDelimiter = AsmToken::Space;
1826 break;
1827 }
1828 }
1829 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001830
1831 // HandleMacroEntry relies on not advancing the lexer here
1832 // to be able to fill in the remaining default parameter values
1833 if (Lexer.is(AsmToken::EndOfStatement))
1834 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001835
1836 // Adjust the current parentheses level.
1837 if (Lexer.is(AsmToken::LParen))
1838 ++ParenLevel;
1839 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1840 --ParenLevel;
1841
1842 // Append the token to the current argument list.
1843 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001844 if (AddTokens)
1845 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001846 Lex();
1847 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001848
1849 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001850 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001851 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001852 return false;
1853}
1854
1855// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001856bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001857 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001858 // Argument delimiter is initially unknown. It will be set by
1859 // ParseMacroArgument()
1860 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001861
1862 // Parse two kinds of macro invocations:
1863 // - macros defined without any parameters accept an arbitrary number of them
1864 // - macros defined with parameters accept at most that many of them
1865 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1866 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001867 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001868
Preston Gurd7b6f2032012-09-19 20:36:12 +00001869 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001870 return true;
1871
Preston Gurd6c9176a2012-09-19 20:29:04 +00001872 if (!MA.empty() || !NParameters)
1873 A.push_back(MA);
1874 else if (NParameters) {
1875 if (!M->Parameters[Parameter].second.empty())
1876 A.push_back(M->Parameters[Parameter].second);
1877 }
Jim Grosbach97146442012-07-30 22:44:17 +00001878
Preston Gurd6c9176a2012-09-19 20:29:04 +00001879 // At the end of the statement, fill in remaining arguments that have
1880 // default values. If there aren't any, then the next argument is
1881 // required but missing
1882 if (Lexer.is(AsmToken::EndOfStatement)) {
1883 if (NParameters && Parameter < NParameters - 1) {
1884 if (M->Parameters[Parameter + 1].second.empty())
1885 return TokError("macro argument '" +
1886 Twine(M->Parameters[Parameter + 1].first) +
1887 "' is missing");
1888 else
1889 continue;
1890 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001891 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001892 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001893
1894 if (Lexer.is(AsmToken::Comma))
1895 Lex();
1896 }
1897 return TokError("Too many arguments");
1898}
1899
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001900const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1901 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1902 return (I == MacroMap.end()) ? NULL : I->getValue();
1903}
1904
1905void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1906 MacroMap[Name] = new MCAsmMacro(Macro);
1907}
1908
1909void AsmParser::UndefineMacro(StringRef Name) {
1910 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1911 if (I != MacroMap.end()) {
1912 delete I->getValue();
1913 MacroMap.erase(I);
1914 }
1915}
1916
1917bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001918 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1919 // this, although we should protect against infinite loops.
1920 if (ActiveMacros.size() == 20)
1921 return TokError("macros cannot be nested more than 20 levels deep");
1922
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001923 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001924 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001925 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001926
Jim Grosbach97146442012-07-30 22:44:17 +00001927 // Remove any trailing empty arguments. Do this after-the-fact as we have
1928 // to keep empty arguments in the middle of the list or positionality
1929 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001930 while (!A.empty() && A.back().empty())
1931 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001932
Rafael Espindola65366442011-06-05 02:43:45 +00001933 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1934 // to hold the macro body with substitutions.
1935 SmallString<256> Buf;
1936 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001937 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001938
Rafael Espindola8a403d32012-08-08 14:51:03 +00001939 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001940 return true;
1941
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001942 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001943 // instantiation.
1944 OS << ".endmacro\n";
1945
Rafael Espindola65366442011-06-05 02:43:45 +00001946 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001947 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001948
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001949 // Create the macro instantiation object and add to the current macro
1950 // instantiation stack.
1951 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001952 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001953 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001954 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001955 ActiveMacros.push_back(MI);
1956
1957 // Jump to the macro instantiation and prime the lexer.
1958 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1959 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1960 Lex();
1961
1962 return false;
1963}
1964
1965void AsmParser::HandleMacroExit() {
1966 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001967 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001968 Lex();
1969
1970 // Pop the instantiation entry.
1971 delete ActiveMacros.back();
1972 ActiveMacros.pop_back();
1973}
1974
Rafael Espindolae71cc862012-01-28 05:57:00 +00001975static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001976 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001977 case MCExpr::Binary: {
1978 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1979 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001980 break;
1981 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001982 case MCExpr::Target:
1983 case MCExpr::Constant:
1984 return false;
1985 case MCExpr::SymbolRef: {
1986 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001987 if (S.isVariable())
1988 return IsUsedIn(Sym, S.getVariableValue());
1989 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001990 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001991 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001992 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001993 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001994
1995 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001996}
1997
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001998bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1999 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002000 // FIXME: Use better location, we should use proper tokens.
2001 SMLoc EqualLoc = Lexer.getLoc();
2002
Daniel Dunbar821e3332009-08-31 08:09:28 +00002003 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00002004 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002005 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002006
Rafael Espindolae71cc862012-01-28 05:57:00 +00002007 // Note: we don't count b as used in "a = b". This is to allow
2008 // a = b
2009 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002010
Daniel Dunbar3f872332009-07-28 16:08:33 +00002011 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002012 return TokError("unexpected token in assignment");
2013
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002014 // Error on assignment to '.'.
2015 if (Name == ".") {
2016 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2017 "(use '.space' or '.org').)"));
2018 }
2019
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002020 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002021 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002022
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002023 // Validate that the LHS is allowed to be a variable (either it has not been
2024 // used as a symbol, or it is an absolute symbol).
2025 MCSymbol *Sym = getContext().LookupSymbol(Name);
2026 if (Sym) {
2027 // Diagnose assignment to a label.
2028 //
2029 // FIXME: Diagnostics. Note the location of the definition as a label.
2030 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002031 if (IsUsedIn(Sym, Value))
2032 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2033 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002034 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002035 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2036 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002037 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002038 return Error(EqualLoc, "redefinition of '" + Name + "'");
2039 else if (!Sym->isVariable())
2040 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002041 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002042 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2043 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002044
2045 // Don't count these checks as uses.
2046 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002047 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002048 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002049
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002050 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002051
2052 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002053 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002054 if (NoDeadStrip)
2055 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2056
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002057
2058 return false;
2059}
2060
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002061/// ParseIdentifier:
2062/// ::= identifier
2063/// ::= string
2064bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002065 // The assembler has relaxed rules for accepting identifiers, in particular we
2066 // allow things like '.globl $foo', which would normally be separate
2067 // tokens. At this level, we have already lexed so we cannot (currently)
2068 // handle this as a context dependent token, instead we detect adjacent tokens
2069 // and return the combined identifier.
2070 if (Lexer.is(AsmToken::Dollar)) {
2071 SMLoc DollarLoc = getLexer().getLoc();
2072
2073 // Consume the dollar sign, and check for a following identifier.
2074 Lex();
2075 if (Lexer.isNot(AsmToken::Identifier))
2076 return true;
2077
2078 // We have a '$' followed by an identifier, make sure they are adjacent.
2079 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2080 return true;
2081
2082 // Construct the joined identifier and consume the token.
2083 Res = StringRef(DollarLoc.getPointer(),
2084 getTok().getIdentifier().size() + 1);
2085 Lex();
2086 return false;
2087 }
2088
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002089 if (Lexer.isNot(AsmToken::Identifier) &&
2090 Lexer.isNot(AsmToken::String))
2091 return true;
2092
Sean Callanan18b83232010-01-19 21:44:56 +00002093 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002094
Sean Callanan79ed1a82010-01-19 20:22:31 +00002095 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002096
2097 return false;
2098}
2099
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002100/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002101/// ::= .equ identifier ',' expression
2102/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002103/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002104bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002105 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002106
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002107 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002108 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002109
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002110 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002111 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002112 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002113
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002114 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002115}
2116
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002117bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002118 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002119
2120 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002121 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002122 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2123 if (Str[i] != '\\') {
2124 Data += Str[i];
2125 continue;
2126 }
2127
2128 // Recognize escaped characters. Note that this escape semantics currently
2129 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2130 ++i;
2131 if (i == e)
2132 return TokError("unexpected backslash at end of string");
2133
2134 // Recognize octal sequences.
2135 if ((unsigned) (Str[i] - '0') <= 7) {
2136 // Consume up to three octal characters.
2137 unsigned Value = Str[i] - '0';
2138
2139 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2140 ++i;
2141 Value = Value * 8 + (Str[i] - '0');
2142
2143 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2144 ++i;
2145 Value = Value * 8 + (Str[i] - '0');
2146 }
2147 }
2148
2149 if (Value > 255)
2150 return TokError("invalid octal escape sequence (out of range)");
2151
2152 Data += (unsigned char) Value;
2153 continue;
2154 }
2155
2156 // Otherwise recognize individual escapes.
2157 switch (Str[i]) {
2158 default:
2159 // Just reject invalid escape sequences for now.
2160 return TokError("invalid escape sequence (unrecognized character)");
2161
2162 case 'b': Data += '\b'; break;
2163 case 'f': Data += '\f'; break;
2164 case 'n': Data += '\n'; break;
2165 case 'r': Data += '\r'; break;
2166 case 't': Data += '\t'; break;
2167 case '"': Data += '"'; break;
2168 case '\\': Data += '\\'; break;
2169 }
2170 }
2171
2172 return false;
2173}
2174
Daniel Dunbara0d14262009-06-24 23:30:00 +00002175/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002176/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2177bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002178 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002179 CheckForValidSection();
2180
Daniel Dunbara0d14262009-06-24 23:30:00 +00002181 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002182 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002183 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002184
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002185 std::string Data;
2186 if (ParseEscapedString(Data))
2187 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002188
2189 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002190 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002191 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2192
Sean Callanan79ed1a82010-01-19 20:22:31 +00002193 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002194
2195 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002196 break;
2197
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002198 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002199 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002200 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002201 }
2202 }
2203
Sean Callanan79ed1a82010-01-19 20:22:31 +00002204 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002205 return false;
2206}
2207
2208/// ParseDirectiveValue
2209/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2210bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002211 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002212 CheckForValidSection();
2213
Daniel Dunbara0d14262009-06-24 23:30:00 +00002214 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002215 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002216 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002217 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218 return true;
2219
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002220 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002221 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2222 assert(Size <= 8 && "Invalid size");
2223 uint64_t IntValue = MCE->getValue();
2224 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2225 return Error(ExprLoc, "literal value out of range for directive");
2226 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2227 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002228 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002229
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002230 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002231 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002232
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002234 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002235 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002236 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002237 }
2238 }
2239
Sean Callanan79ed1a82010-01-19 20:22:31 +00002240 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002241 return false;
2242}
2243
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002244/// ParseDirectiveRealValue
2245/// ::= (.single | .double) [ expression (, expression)* ]
2246bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2247 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2248 CheckForValidSection();
2249
2250 for (;;) {
2251 // We don't truly support arithmetic on floating point expressions, so we
2252 // have to manually parse unary prefixes.
2253 bool IsNeg = false;
2254 if (getLexer().is(AsmToken::Minus)) {
2255 Lex();
2256 IsNeg = true;
2257 } else if (getLexer().is(AsmToken::Plus))
2258 Lex();
2259
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002260 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002261 getLexer().isNot(AsmToken::Real) &&
2262 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002263 return TokError("unexpected token in directive");
2264
2265 // Convert to an APFloat.
2266 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002267 StringRef IDVal = getTok().getString();
2268 if (getLexer().is(AsmToken::Identifier)) {
2269 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2270 Value = APFloat::getInf(Semantics);
2271 else if (!IDVal.compare_lower("nan"))
2272 Value = APFloat::getNaN(Semantics, false, ~0);
2273 else
2274 return TokError("invalid floating point literal");
2275 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002276 APFloat::opInvalidOp)
2277 return TokError("invalid floating point literal");
2278 if (IsNeg)
2279 Value.changeSign();
2280
2281 // Consume the numeric token.
2282 Lex();
2283
2284 // Emit the value as an integer.
2285 APInt AsInt = Value.bitcastToAPInt();
2286 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2287 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2288
2289 if (getLexer().is(AsmToken::EndOfStatement))
2290 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002291
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002292 if (getLexer().isNot(AsmToken::Comma))
2293 return TokError("unexpected token in directive");
2294 Lex();
2295 }
2296 }
2297
2298 Lex();
2299 return false;
2300}
2301
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002302/// ParseDirectiveZero
2303/// ::= .zero expression
2304bool AsmParser::ParseDirectiveZero() {
2305 CheckForValidSection();
2306
2307 int64_t NumBytes;
2308 if (ParseAbsoluteExpression(NumBytes))
2309 return true;
2310
Rafael Espindolae452b172010-10-05 19:42:57 +00002311 int64_t Val = 0;
2312 if (getLexer().is(AsmToken::Comma)) {
2313 Lex();
2314 if (ParseAbsoluteExpression(Val))
2315 return true;
2316 }
2317
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002318 if (getLexer().isNot(AsmToken::EndOfStatement))
2319 return TokError("unexpected token in '.zero' directive");
2320
2321 Lex();
2322
Rafael Espindolae452b172010-10-05 19:42:57 +00002323 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002324
2325 return false;
2326}
2327
Daniel Dunbara0d14262009-06-24 23:30:00 +00002328/// ParseDirectiveFill
2329/// ::= .fill expression , expression , expression
2330bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002331 CheckForValidSection();
2332
Daniel Dunbara0d14262009-06-24 23:30:00 +00002333 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002334 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002335 return true;
2336
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002337 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002338 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002339 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002340
Daniel Dunbara0d14262009-06-24 23:30:00 +00002341 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002342 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002343 return true;
2344
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002345 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002346 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002347 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002348
Daniel Dunbara0d14262009-06-24 23:30:00 +00002349 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002350 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002351 return true;
2352
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002353 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002354 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002355
Sean Callanan79ed1a82010-01-19 20:22:31 +00002356 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002357
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002358 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2359 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002360
2361 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002362 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002363
2364 return false;
2365}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002366
2367/// ParseDirectiveOrg
2368/// ::= .org expression [ , expression ]
2369bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002370 CheckForValidSection();
2371
Daniel Dunbar821e3332009-08-31 08:09:28 +00002372 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002373 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002374 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002375 return true;
2376
2377 // Parse optional fill expression.
2378 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002379 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2380 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002381 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002382 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002383
Daniel Dunbar475839e2009-06-29 20:37:27 +00002384 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002385 return true;
2386
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002387 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002388 return TokError("unexpected token in '.org' directive");
2389 }
2390
Sean Callanan79ed1a82010-01-19 20:22:31 +00002391 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002392
Jim Grosbachebd4c052012-01-27 00:37:08 +00002393 // Only limited forms of relocatable expressions are accepted here, it
2394 // has to be relative to the current section. The streamer will return
2395 // 'true' if the expression wasn't evaluatable.
2396 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2397 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002398
2399 return false;
2400}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002401
2402/// ParseDirectiveAlign
2403/// ::= {.align, ...} expression [ , expression [ , expression ]]
2404bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002405 CheckForValidSection();
2406
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002407 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002408 int64_t Alignment;
2409 if (ParseAbsoluteExpression(Alignment))
2410 return true;
2411
2412 SMLoc MaxBytesLoc;
2413 bool HasFillExpr = false;
2414 int64_t FillExpr = 0;
2415 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2417 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002418 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002419 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002420
2421 // The fill expression can be omitted while specifying a maximum number of
2422 // alignment bytes, e.g:
2423 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002425 HasFillExpr = true;
2426 if (ParseAbsoluteExpression(FillExpr))
2427 return true;
2428 }
2429
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002430 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2431 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002432 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002433 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002434
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002435 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002436 if (ParseAbsoluteExpression(MaxBytesToFill))
2437 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002438
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002439 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002440 return TokError("unexpected token in directive");
2441 }
2442 }
2443
Sean Callanan79ed1a82010-01-19 20:22:31 +00002444 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002445
Daniel Dunbar648ac512010-05-17 21:54:30 +00002446 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002447 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448
2449 // Compute alignment in bytes.
2450 if (IsPow2) {
2451 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002452 if (Alignment >= 32) {
2453 Error(AlignmentLoc, "invalid alignment value");
2454 Alignment = 31;
2455 }
2456
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002457 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458 }
2459
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002460 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002461 if (MaxBytesLoc.isValid()) {
2462 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002463 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2464 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002465 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002466 }
2467
2468 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002469 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2470 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002471 MaxBytesToFill = 0;
2472 }
2473 }
2474
Daniel Dunbar648ac512010-05-17 21:54:30 +00002475 // Check whether we should use optimal code alignment for this .align
2476 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002477 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002478 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2479 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002480 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002481 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002482 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002483 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2484 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002485 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002486
2487 return false;
2488}
2489
Eli Bendersky6ee13082013-01-15 22:59:42 +00002490/// ParseDirectiveFile
2491/// ::= .file [number] filename
2492/// ::= .file number directory filename
2493bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2494 // FIXME: I'm not sure what this is.
2495 int64_t FileNumber = -1;
2496 SMLoc FileNumberLoc = getLexer().getLoc();
2497 if (getLexer().is(AsmToken::Integer)) {
2498 FileNumber = getTok().getIntVal();
2499 Lex();
2500
2501 if (FileNumber < 1)
2502 return TokError("file number less than one");
2503 }
2504
2505 if (getLexer().isNot(AsmToken::String))
2506 return TokError("unexpected token in '.file' directive");
2507
2508 // Usually the directory and filename together, otherwise just the directory.
2509 StringRef Path = getTok().getString();
2510 Path = Path.substr(1, Path.size()-2);
2511 Lex();
2512
2513 StringRef Directory;
2514 StringRef Filename;
2515 if (getLexer().is(AsmToken::String)) {
2516 if (FileNumber == -1)
2517 return TokError("explicit path specified, but no file number");
2518 Filename = getTok().getString();
2519 Filename = Filename.substr(1, Filename.size()-2);
2520 Directory = Path;
2521 Lex();
2522 } else {
2523 Filename = Path;
2524 }
2525
2526 if (getLexer().isNot(AsmToken::EndOfStatement))
2527 return TokError("unexpected token in '.file' directive");
2528
2529 if (FileNumber == -1)
2530 getStreamer().EmitFileDirective(Filename);
2531 else {
2532 if (getContext().getGenDwarfForAssembly() == true)
2533 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2534 "used to generate dwarf debug info for assembly code");
2535
2536 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2537 Error(FileNumberLoc, "file number already allocated");
2538 }
2539
2540 return false;
2541}
2542
2543/// ParseDirectiveLine
2544/// ::= .line [number]
2545bool AsmParser::ParseDirectiveLine() {
2546 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2547 if (getLexer().isNot(AsmToken::Integer))
2548 return TokError("unexpected token in '.line' directive");
2549
2550 int64_t LineNumber = getTok().getIntVal();
2551 (void) LineNumber;
2552 Lex();
2553
2554 // FIXME: Do something with the .line.
2555 }
2556
2557 if (getLexer().isNot(AsmToken::EndOfStatement))
2558 return TokError("unexpected token in '.line' directive");
2559
2560 return false;
2561}
2562
2563/// ParseDirectiveLoc
2564/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2565/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2566/// The first number is a file number, must have been previously assigned with
2567/// a .file directive, the second number is the line number and optionally the
2568/// third number is a column position (zero if not specified). The remaining
2569/// optional items are .loc sub-directives.
2570bool AsmParser::ParseDirectiveLoc() {
2571 if (getLexer().isNot(AsmToken::Integer))
2572 return TokError("unexpected token in '.loc' directive");
2573 int64_t FileNumber = getTok().getIntVal();
2574 if (FileNumber < 1)
2575 return TokError("file number less than one in '.loc' directive");
2576 if (!getContext().isValidDwarfFileNumber(FileNumber))
2577 return TokError("unassigned file number in '.loc' directive");
2578 Lex();
2579
2580 int64_t LineNumber = 0;
2581 if (getLexer().is(AsmToken::Integer)) {
2582 LineNumber = getTok().getIntVal();
2583 if (LineNumber < 1)
2584 return TokError("line number less than one in '.loc' directive");
2585 Lex();
2586 }
2587
2588 int64_t ColumnPos = 0;
2589 if (getLexer().is(AsmToken::Integer)) {
2590 ColumnPos = getTok().getIntVal();
2591 if (ColumnPos < 0)
2592 return TokError("column position less than zero in '.loc' directive");
2593 Lex();
2594 }
2595
2596 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2597 unsigned Isa = 0;
2598 int64_t Discriminator = 0;
2599 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2600 for (;;) {
2601 if (getLexer().is(AsmToken::EndOfStatement))
2602 break;
2603
2604 StringRef Name;
2605 SMLoc Loc = getTok().getLoc();
2606 if (ParseIdentifier(Name))
2607 return TokError("unexpected token in '.loc' directive");
2608
2609 if (Name == "basic_block")
2610 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2611 else if (Name == "prologue_end")
2612 Flags |= DWARF2_FLAG_PROLOGUE_END;
2613 else if (Name == "epilogue_begin")
2614 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2615 else if (Name == "is_stmt") {
2616 Loc = getTok().getLoc();
2617 const MCExpr *Value;
2618 if (ParseExpression(Value))
2619 return true;
2620 // The expression must be the constant 0 or 1.
2621 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2622 int Value = MCE->getValue();
2623 if (Value == 0)
2624 Flags &= ~DWARF2_FLAG_IS_STMT;
2625 else if (Value == 1)
2626 Flags |= DWARF2_FLAG_IS_STMT;
2627 else
2628 return Error(Loc, "is_stmt value not 0 or 1");
2629 }
2630 else {
2631 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2632 }
2633 }
2634 else if (Name == "isa") {
2635 Loc = getTok().getLoc();
2636 const MCExpr *Value;
2637 if (ParseExpression(Value))
2638 return true;
2639 // The expression must be a constant greater or equal to 0.
2640 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2641 int Value = MCE->getValue();
2642 if (Value < 0)
2643 return Error(Loc, "isa number less than zero");
2644 Isa = Value;
2645 }
2646 else {
2647 return Error(Loc, "isa number not a constant value");
2648 }
2649 }
2650 else if (Name == "discriminator") {
2651 if (ParseAbsoluteExpression(Discriminator))
2652 return true;
2653 }
2654 else {
2655 return Error(Loc, "unknown sub-directive in '.loc' directive");
2656 }
2657
2658 if (getLexer().is(AsmToken::EndOfStatement))
2659 break;
2660 }
2661 }
2662
2663 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2664 Isa, Discriminator, StringRef());
2665
2666 return false;
2667}
2668
2669/// ParseDirectiveStabs
2670/// ::= .stabs string, number, number, number
2671bool AsmParser::ParseDirectiveStabs() {
2672 return TokError("unsupported directive '.stabs'");
2673}
2674
2675/// ParseDirectiveCFISections
2676/// ::= .cfi_sections section [, section]
2677bool AsmParser::ParseDirectiveCFISections() {
2678 StringRef Name;
2679 bool EH = false;
2680 bool Debug = false;
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 if (getLexer().is(AsmToken::Comma)) {
2691 Lex();
2692
2693 if (ParseIdentifier(Name))
2694 return TokError("Expected an identifier");
2695
2696 if (Name == ".eh_frame")
2697 EH = true;
2698 else if (Name == ".debug_frame")
2699 Debug = true;
2700 }
2701
2702 getStreamer().EmitCFISections(EH, Debug);
2703 return false;
2704}
2705
2706/// ParseDirectiveCFIStartProc
2707/// ::= .cfi_startproc
2708bool AsmParser::ParseDirectiveCFIStartProc() {
2709 getStreamer().EmitCFIStartProc();
2710 return false;
2711}
2712
2713/// ParseDirectiveCFIEndProc
2714/// ::= .cfi_endproc
2715bool AsmParser::ParseDirectiveCFIEndProc() {
2716 getStreamer().EmitCFIEndProc();
2717 return false;
2718}
2719
2720/// ParseRegisterOrRegisterNumber - parse register name or number.
2721bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2722 SMLoc DirectiveLoc) {
2723 unsigned RegNo;
2724
2725 if (getLexer().isNot(AsmToken::Integer)) {
2726 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2727 return true;
2728 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2729 } else
2730 return ParseAbsoluteExpression(Register);
2731
2732 return false;
2733}
2734
2735/// ParseDirectiveCFIDefCfa
2736/// ::= .cfi_def_cfa register, offset
2737bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2738 int64_t Register = 0;
2739 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2740 return true;
2741
2742 if (getLexer().isNot(AsmToken::Comma))
2743 return TokError("unexpected token in directive");
2744 Lex();
2745
2746 int64_t Offset = 0;
2747 if (ParseAbsoluteExpression(Offset))
2748 return true;
2749
2750 getStreamer().EmitCFIDefCfa(Register, Offset);
2751 return false;
2752}
2753
2754/// ParseDirectiveCFIDefCfaOffset
2755/// ::= .cfi_def_cfa_offset offset
2756bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2757 int64_t Offset = 0;
2758 if (ParseAbsoluteExpression(Offset))
2759 return true;
2760
2761 getStreamer().EmitCFIDefCfaOffset(Offset);
2762 return false;
2763}
2764
2765/// ParseDirectiveCFIRegister
2766/// ::= .cfi_register register, register
2767bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2768 int64_t Register1 = 0;
2769 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2770 return true;
2771
2772 if (getLexer().isNot(AsmToken::Comma))
2773 return TokError("unexpected token in directive");
2774 Lex();
2775
2776 int64_t Register2 = 0;
2777 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2778 return true;
2779
2780 getStreamer().EmitCFIRegister(Register1, Register2);
2781 return false;
2782}
2783
2784/// ParseDirectiveCFIAdjustCfaOffset
2785/// ::= .cfi_adjust_cfa_offset adjustment
2786bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2787 int64_t Adjustment = 0;
2788 if (ParseAbsoluteExpression(Adjustment))
2789 return true;
2790
2791 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2792 return false;
2793}
2794
2795/// ParseDirectiveCFIDefCfaRegister
2796/// ::= .cfi_def_cfa_register register
2797bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2798 int64_t Register = 0;
2799 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2800 return true;
2801
2802 getStreamer().EmitCFIDefCfaRegister(Register);
2803 return false;
2804}
2805
2806/// ParseDirectiveCFIOffset
2807/// ::= .cfi_offset register, offset
2808bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2809 int64_t Register = 0;
2810 int64_t Offset = 0;
2811
2812 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2813 return true;
2814
2815 if (getLexer().isNot(AsmToken::Comma))
2816 return TokError("unexpected token in directive");
2817 Lex();
2818
2819 if (ParseAbsoluteExpression(Offset))
2820 return true;
2821
2822 getStreamer().EmitCFIOffset(Register, Offset);
2823 return false;
2824}
2825
2826/// ParseDirectiveCFIRelOffset
2827/// ::= .cfi_rel_offset register, offset
2828bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2829 int64_t Register = 0;
2830
2831 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2832 return true;
2833
2834 if (getLexer().isNot(AsmToken::Comma))
2835 return TokError("unexpected token in directive");
2836 Lex();
2837
2838 int64_t Offset = 0;
2839 if (ParseAbsoluteExpression(Offset))
2840 return true;
2841
2842 getStreamer().EmitCFIRelOffset(Register, Offset);
2843 return false;
2844}
2845
2846static bool isValidEncoding(int64_t Encoding) {
2847 if (Encoding & ~0xff)
2848 return false;
2849
2850 if (Encoding == dwarf::DW_EH_PE_omit)
2851 return true;
2852
2853 const unsigned Format = Encoding & 0xf;
2854 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2855 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2856 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2857 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2858 return false;
2859
2860 const unsigned Application = Encoding & 0x70;
2861 if (Application != dwarf::DW_EH_PE_absptr &&
2862 Application != dwarf::DW_EH_PE_pcrel)
2863 return false;
2864
2865 return true;
2866}
2867
2868/// ParseDirectiveCFIPersonalityOrLsda
2869/// IsPersonality true for cfi_personality, false for cfi_lsda
2870/// ::= .cfi_personality encoding, [symbol_name]
2871/// ::= .cfi_lsda encoding, [symbol_name]
2872bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2873 int64_t Encoding = 0;
2874 if (ParseAbsoluteExpression(Encoding))
2875 return true;
2876 if (Encoding == dwarf::DW_EH_PE_omit)
2877 return false;
2878
2879 if (!isValidEncoding(Encoding))
2880 return TokError("unsupported encoding.");
2881
2882 if (getLexer().isNot(AsmToken::Comma))
2883 return TokError("unexpected token in directive");
2884 Lex();
2885
2886 StringRef Name;
2887 if (ParseIdentifier(Name))
2888 return TokError("expected identifier in directive");
2889
2890 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2891
2892 if (IsPersonality)
2893 getStreamer().EmitCFIPersonality(Sym, Encoding);
2894 else
2895 getStreamer().EmitCFILsda(Sym, Encoding);
2896 return false;
2897}
2898
2899/// ParseDirectiveCFIRememberState
2900/// ::= .cfi_remember_state
2901bool AsmParser::ParseDirectiveCFIRememberState() {
2902 getStreamer().EmitCFIRememberState();
2903 return false;
2904}
2905
2906/// ParseDirectiveCFIRestoreState
2907/// ::= .cfi_remember_state
2908bool AsmParser::ParseDirectiveCFIRestoreState() {
2909 getStreamer().EmitCFIRestoreState();
2910 return false;
2911}
2912
2913/// ParseDirectiveCFISameValue
2914/// ::= .cfi_same_value register
2915bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2916 int64_t Register = 0;
2917
2918 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2919 return true;
2920
2921 getStreamer().EmitCFISameValue(Register);
2922 return false;
2923}
2924
2925/// ParseDirectiveCFIRestore
2926/// ::= .cfi_restore register
2927bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2928 int64_t Register = 0;
2929 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2930 return true;
2931
2932 getStreamer().EmitCFIRestore(Register);
2933 return false;
2934}
2935
2936/// ParseDirectiveCFIEscape
2937/// ::= .cfi_escape expression[,...]
2938bool AsmParser::ParseDirectiveCFIEscape() {
2939 std::string Values;
2940 int64_t CurrValue;
2941 if (ParseAbsoluteExpression(CurrValue))
2942 return true;
2943
2944 Values.push_back((uint8_t)CurrValue);
2945
2946 while (getLexer().is(AsmToken::Comma)) {
2947 Lex();
2948
2949 if (ParseAbsoluteExpression(CurrValue))
2950 return true;
2951
2952 Values.push_back((uint8_t)CurrValue);
2953 }
2954
2955 getStreamer().EmitCFIEscape(Values);
2956 return false;
2957}
2958
2959/// ParseDirectiveCFISignalFrame
2960/// ::= .cfi_signal_frame
2961bool AsmParser::ParseDirectiveCFISignalFrame() {
2962 if (getLexer().isNot(AsmToken::EndOfStatement))
2963 return Error(getLexer().getLoc(),
2964 "unexpected token in '.cfi_signal_frame'");
2965
2966 getStreamer().EmitCFISignalFrame();
2967 return false;
2968}
2969
2970/// ParseDirectiveCFIUndefined
2971/// ::= .cfi_undefined register
2972bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2973 int64_t Register = 0;
2974
2975 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2976 return true;
2977
2978 getStreamer().EmitCFIUndefined(Register);
2979 return false;
2980}
2981
2982/// ParseDirectiveMacrosOnOff
2983/// ::= .macros_on
2984/// ::= .macros_off
2985bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2986 if (getLexer().isNot(AsmToken::EndOfStatement))
2987 return Error(getLexer().getLoc(),
2988 "unexpected token in '" + Directive + "' directive");
2989
2990 SetMacrosEnabled(Directive == ".macros_on");
2991 return false;
2992}
2993
2994/// ParseDirectiveMacro
2995/// ::= .macro name [parameters]
2996bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2997 StringRef Name;
2998 if (ParseIdentifier(Name))
2999 return TokError("expected identifier in '.macro' directive");
3000
3001 MCAsmMacroParameters Parameters;
3002 // Argument delimiter is initially unknown. It will be set by
3003 // ParseMacroArgument()
3004 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3005 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3006 for (;;) {
3007 MCAsmMacroParameter Parameter;
3008 if (ParseIdentifier(Parameter.first))
3009 return TokError("expected identifier in '.macro' directive");
3010
3011 if (getLexer().is(AsmToken::Equal)) {
3012 Lex();
3013 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3014 return true;
3015 }
3016
3017 Parameters.push_back(Parameter);
3018
3019 if (getLexer().is(AsmToken::Comma))
3020 Lex();
3021 else if (getLexer().is(AsmToken::EndOfStatement))
3022 break;
3023 }
3024 }
3025
3026 // Eat the end of statement.
3027 Lex();
3028
3029 AsmToken EndToken, StartToken = getTok();
3030
3031 // Lex the macro definition.
3032 for (;;) {
3033 // Check whether we have reached the end of the file.
3034 if (getLexer().is(AsmToken::Eof))
3035 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3036
3037 // Otherwise, check whether we have reach the .endmacro.
3038 if (getLexer().is(AsmToken::Identifier) &&
3039 (getTok().getIdentifier() == ".endm" ||
3040 getTok().getIdentifier() == ".endmacro")) {
3041 EndToken = getTok();
3042 Lex();
3043 if (getLexer().isNot(AsmToken::EndOfStatement))
3044 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3045 "' directive");
3046 break;
3047 }
3048
3049 // Otherwise, scan til the end of the statement.
3050 EatToEndOfStatement();
3051 }
3052
3053 if (LookupMacro(Name)) {
3054 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3055 }
3056
3057 const char *BodyStart = StartToken.getLoc().getPointer();
3058 const char *BodyEnd = EndToken.getLoc().getPointer();
3059 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003060 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003061 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3062 return false;
3063}
3064
Kevin Enderby221514e2013-01-22 21:44:53 +00003065/// CheckForBadMacro
3066///
3067/// With the support added for named parameters there may be code out there that
3068/// is transitioning from positional parameters. In versions of gas that did
3069/// not support named parameters they would be ignored on the macro defintion.
3070/// But to support both styles of parameters this is not possible so if a macro
3071/// defintion has named parameters but does not use them and has what appears
3072/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3073/// warning that the positional parameter found in body which have no effect.
3074/// Hoping the developer will either remove the named parameters from the macro
3075/// definiton so the positional parameters get used if that was what was
3076/// intended or change the macro to use the named parameters. It is possible
3077/// this warning will trigger when the none of the named parameters are used
3078/// and the strings like $1 are infact to simply to be passed trough unchanged.
3079void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3080 StringRef Body,
3081 MCAsmMacroParameters Parameters) {
3082 // If this macro is not defined with named parameters the warning we are
3083 // checking for here doesn't apply.
3084 unsigned NParameters = Parameters.size();
3085 if (NParameters == 0)
3086 return;
3087
3088 bool NamedParametersFound = false;
3089 bool PositionalParametersFound = false;
3090
3091 // Look at the body of the macro for use of both the named parameters and what
3092 // are likely to be positional parameters. This is what expandMacro() is
3093 // doing when it finds the parameters in the body.
3094 while (!Body.empty()) {
3095 // Scan for the next possible parameter.
3096 std::size_t End = Body.size(), Pos = 0;
3097 for (; Pos != End; ++Pos) {
3098 // Check for a substitution or escape.
3099 // This macro is defined with parameters, look for \foo, \bar, etc.
3100 if (Body[Pos] == '\\' && Pos + 1 != End)
3101 break;
3102
3103 // This macro should have parameters, but look for $0, $1, ..., $n too.
3104 if (Body[Pos] != '$' || Pos + 1 == End)
3105 continue;
3106 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003107 if (Next == '$' || Next == 'n' ||
3108 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003109 break;
3110 }
3111
3112 // Check if we reached the end.
3113 if (Pos == End)
3114 break;
3115
3116 if (Body[Pos] == '$') {
3117 switch (Body[Pos+1]) {
3118 // $$ => $
3119 case '$':
3120 break;
3121
3122 // $n => number of arguments
3123 case 'n':
3124 PositionalParametersFound = true;
3125 break;
3126
3127 // $[0-9] => argument
3128 default: {
3129 PositionalParametersFound = true;
3130 break;
3131 }
3132 }
3133 Pos += 2;
3134 } else {
3135 unsigned I = Pos + 1;
3136 while (isIdentifierChar(Body[I]) && I + 1 != End)
3137 ++I;
3138
3139 const char *Begin = Body.data() + Pos +1;
3140 StringRef Argument(Begin, I - (Pos +1));
3141 unsigned Index = 0;
3142 for (; Index < NParameters; ++Index)
3143 if (Parameters[Index].first == Argument)
3144 break;
3145
3146 if (Index == NParameters) {
3147 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3148 Pos += 3;
3149 else {
3150 Pos = I;
3151 }
3152 } else {
3153 NamedParametersFound = true;
3154 Pos += 1 + Argument.size();
3155 }
3156 }
3157 // Update the scan point.
3158 Body = Body.substr(Pos);
3159 }
3160
3161 if (!NamedParametersFound && PositionalParametersFound)
3162 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3163 "used in macro body, possible positional parameter "
3164 "found in body which will have no effect");
3165}
3166
Eli Bendersky6ee13082013-01-15 22:59:42 +00003167/// ParseDirectiveEndMacro
3168/// ::= .endm
3169/// ::= .endmacro
3170bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3171 if (getLexer().isNot(AsmToken::EndOfStatement))
3172 return TokError("unexpected token in '" + Directive + "' directive");
3173
3174 // If we are inside a macro instantiation, terminate the current
3175 // instantiation.
3176 if (InsideMacroInstantiation()) {
3177 HandleMacroExit();
3178 return false;
3179 }
3180
3181 // Otherwise, this .endmacro is a stray entry in the file; well formed
3182 // .endmacro directives are handled during the macro definition parsing.
3183 return TokError("unexpected '" + Directive + "' in file, "
3184 "no current macro definition");
3185}
3186
3187/// ParseDirectivePurgeMacro
3188/// ::= .purgem
3189bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3190 StringRef Name;
3191 if (ParseIdentifier(Name))
3192 return TokError("expected identifier in '.purgem' directive");
3193
3194 if (getLexer().isNot(AsmToken::EndOfStatement))
3195 return TokError("unexpected token in '.purgem' directive");
3196
3197 if (!LookupMacro(Name))
3198 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3199
3200 UndefineMacro(Name);
3201 return false;
3202}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003203
3204/// ParseDirectiveBundleAlignMode
3205/// ::= {.bundle_align_mode} expression
3206bool AsmParser::ParseDirectiveBundleAlignMode() {
3207 CheckForValidSection();
3208
3209 // Expect a single argument: an expression that evaluates to a constant
3210 // in the inclusive range 0-30.
3211 SMLoc ExprLoc = getLexer().getLoc();
3212 int64_t AlignSizePow2;
3213 if (ParseAbsoluteExpression(AlignSizePow2))
3214 return true;
3215 else if (getLexer().isNot(AsmToken::EndOfStatement))
3216 return TokError("unexpected token after expression in"
3217 " '.bundle_align_mode' directive");
3218 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3219 return Error(ExprLoc,
3220 "invalid bundle alignment size (expected between 0 and 30)");
3221
3222 Lex();
3223
3224 // Because of AlignSizePow2's verified range we can safely truncate it to
3225 // unsigned.
3226 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3227 return false;
3228}
3229
3230/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003231/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003232bool AsmParser::ParseDirectiveBundleLock() {
3233 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003234 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003235
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3237 StringRef Option;
3238 SMLoc Loc = getTok().getLoc();
3239 const char *kInvalidOptionError =
3240 "invalid option for '.bundle_lock' directive";
3241
3242 if (ParseIdentifier(Option))
3243 return Error(Loc, kInvalidOptionError);
3244
3245 if (Option != "align_to_end")
3246 return Error(Loc, kInvalidOptionError);
3247 else if (getLexer().isNot(AsmToken::EndOfStatement))
3248 return Error(Loc,
3249 "unexpected token after '.bundle_lock' directive option");
3250 AlignToEnd = true;
3251 }
3252
Eli Bendersky4766ef42012-12-20 19:05:53 +00003253 Lex();
3254
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003255 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003256 return false;
3257}
3258
3259/// ParseDirectiveBundleLock
3260/// ::= {.bundle_lock}
3261bool AsmParser::ParseDirectiveBundleUnlock() {
3262 CheckForValidSection();
3263
3264 if (getLexer().isNot(AsmToken::EndOfStatement))
3265 return TokError("unexpected token in '.bundle_unlock' directive");
3266 Lex();
3267
3268 getStreamer().EmitBundleUnlock();
3269 return false;
3270}
3271
Eli Bendersky6ee13082013-01-15 22:59:42 +00003272/// ParseDirectiveSpace
3273/// ::= (.skip | .space) expression [ , expression ]
3274bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3275 CheckForValidSection();
3276
3277 int64_t NumBytes;
3278 if (ParseAbsoluteExpression(NumBytes))
3279 return true;
3280
3281 int64_t FillExpr = 0;
3282 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3283 if (getLexer().isNot(AsmToken::Comma))
3284 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3285 Lex();
3286
3287 if (ParseAbsoluteExpression(FillExpr))
3288 return true;
3289
3290 if (getLexer().isNot(AsmToken::EndOfStatement))
3291 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3292 }
3293
3294 Lex();
3295
3296 if (NumBytes <= 0)
3297 return TokError("invalid number of bytes in '" +
3298 Twine(IDVal) + "' directive");
3299
3300 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3301 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3302
3303 return false;
3304}
3305
3306/// ParseDirectiveLEB128
3307/// ::= (.sleb128 | .uleb128) expression
3308bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3309 CheckForValidSection();
3310 const MCExpr *Value;
3311
3312 if (ParseExpression(Value))
3313 return true;
3314
3315 if (getLexer().isNot(AsmToken::EndOfStatement))
3316 return TokError("unexpected token in directive");
3317
3318 if (Signed)
3319 getStreamer().EmitSLEB128Value(Value);
3320 else
3321 getStreamer().EmitULEB128Value(Value);
3322
3323 return false;
3324}
3325
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003326/// ParseDirectiveSymbolAttribute
3327/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003328bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003329 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003330 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003331 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003332 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003333
3334 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003335 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003336
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003337 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003338
Jim Grosbach10ec6502011-09-15 17:56:49 +00003339 // Assembler local symbols don't make any sense here. Complain loudly.
3340 if (Sym->isTemporary())
3341 return Error(Loc, "non-local symbol required in directive");
3342
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003343 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003344
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003345 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003346 break;
3347
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003348 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003349 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003350 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003351 }
3352 }
3353
Sean Callanan79ed1a82010-01-19 20:22:31 +00003354 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003355 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003356}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003357
3358/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003359/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3360bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003361 CheckForValidSection();
3362
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003363 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003364 StringRef Name;
3365 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003366 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003367
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003368 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003369 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003370
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003371 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003372 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003373 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003374
3375 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003376 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003377 if (ParseAbsoluteExpression(Size))
3378 return true;
3379
3380 int64_t Pow2Alignment = 0;
3381 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003382 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003383 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003384 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003385 if (ParseAbsoluteExpression(Pow2Alignment))
3386 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003387
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003388 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3389 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003390 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3391
Chris Lattner258281d2010-01-19 06:22:22 +00003392 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003393 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3394 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003395 if (!isPowerOf2_64(Pow2Alignment))
3396 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3397 Pow2Alignment = Log2_64(Pow2Alignment);
3398 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003399 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003400
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003401 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003402 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003403
Sean Callanan79ed1a82010-01-19 20:22:31 +00003404 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003405
Chris Lattner1fc3d752009-07-09 17:25:12 +00003406 // NOTE: a size of zero for a .comm should create a undefined symbol
3407 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003408 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003409 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3410 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003411
Eric Christopherc260a3e2010-05-14 01:38:54 +00003412 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003413 // may internally end up wanting an alignment in bytes.
3414 // FIXME: Diagnose overflow.
3415 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003416 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3417 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003418
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003419 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003420 return Error(IDLoc, "invalid symbol redefinition");
3421
Chris Lattner1fc3d752009-07-09 17:25:12 +00003422 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003423 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003424 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003425 return false;
3426 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003427
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003428 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003429 return false;
3430}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003431
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003432/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003433/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003434bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003435 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003436 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003437
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003438 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003439 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003440 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003441
Sean Callanan79ed1a82010-01-19 20:22:31 +00003442 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003443
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003444 if (Str.empty())
3445 Error(Loc, ".abort detected. Assembly stopping.");
3446 else
3447 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003448 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003449
3450 return false;
3451}
Kevin Enderby71148242009-07-14 21:35:03 +00003452
Kevin Enderby1f049b22009-07-14 23:21:55 +00003453/// ParseDirectiveInclude
3454/// ::= .include "filename"
3455bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003456 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003457 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003458
Sean Callanan18b83232010-01-19 21:44:56 +00003459 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003460 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003461 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003462
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003463 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003464 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003465
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003466 // Strip the quotes.
3467 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003468
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003469 // Attempt to switch the lexer to the included file before consuming the end
3470 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003471 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003472 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003473 return true;
3474 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003475
3476 return false;
3477}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003478
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003479/// ParseDirectiveIncbin
3480/// ::= .incbin "filename"
3481bool AsmParser::ParseDirectiveIncbin() {
3482 if (getLexer().isNot(AsmToken::String))
3483 return TokError("expected string in '.incbin' directive");
3484
3485 std::string Filename = getTok().getString();
3486 SMLoc IncbinLoc = getLexer().getLoc();
3487 Lex();
3488
3489 if (getLexer().isNot(AsmToken::EndOfStatement))
3490 return TokError("unexpected token in '.incbin' directive");
3491
3492 // Strip the quotes.
3493 Filename = Filename.substr(1, Filename.size()-2);
3494
3495 // Attempt to process the included file.
3496 if (ProcessIncbinFile(Filename)) {
3497 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3498 return true;
3499 }
3500
3501 return false;
3502}
3503
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003504/// ParseDirectiveIf
3505/// ::= .if expression
3506bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003507 TheCondStack.push_back(TheCondState);
3508 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003509 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003510 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003511 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003512 int64_t ExprValue;
3513 if (ParseAbsoluteExpression(ExprValue))
3514 return true;
3515
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003516 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003517 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003518
Sean Callanan79ed1a82010-01-19 20:22:31 +00003519 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003520
3521 TheCondState.CondMet = ExprValue;
3522 TheCondState.Ignore = !TheCondState.CondMet;
3523 }
3524
3525 return false;
3526}
3527
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003528/// ParseDirectiveIfb
3529/// ::= .ifb string
3530bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3531 TheCondStack.push_back(TheCondState);
3532 TheCondState.TheCond = AsmCond::IfCond;
3533
Benjamin Kramer29739e72012-05-12 16:52:21 +00003534 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003535 EatToEndOfStatement();
3536 } else {
3537 StringRef Str = ParseStringToEndOfStatement();
3538
3539 if (getLexer().isNot(AsmToken::EndOfStatement))
3540 return TokError("unexpected token in '.ifb' directive");
3541
3542 Lex();
3543
3544 TheCondState.CondMet = ExpectBlank == Str.empty();
3545 TheCondState.Ignore = !TheCondState.CondMet;
3546 }
3547
3548 return false;
3549}
3550
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003551/// ParseDirectiveIfc
3552/// ::= .ifc string1, string2
3553bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3554 TheCondStack.push_back(TheCondState);
3555 TheCondState.TheCond = AsmCond::IfCond;
3556
Benjamin Kramer29739e72012-05-12 16:52:21 +00003557 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003558 EatToEndOfStatement();
3559 } else {
3560 StringRef Str1 = ParseStringToComma();
3561
3562 if (getLexer().isNot(AsmToken::Comma))
3563 return TokError("unexpected token in '.ifc' directive");
3564
3565 Lex();
3566
3567 StringRef Str2 = ParseStringToEndOfStatement();
3568
3569 if (getLexer().isNot(AsmToken::EndOfStatement))
3570 return TokError("unexpected token in '.ifc' directive");
3571
3572 Lex();
3573
3574 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3575 TheCondState.Ignore = !TheCondState.CondMet;
3576 }
3577
3578 return false;
3579}
3580
3581/// ParseDirectiveIfdef
3582/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003583bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3584 StringRef Name;
3585 TheCondStack.push_back(TheCondState);
3586 TheCondState.TheCond = AsmCond::IfCond;
3587
3588 if (TheCondState.Ignore) {
3589 EatToEndOfStatement();
3590 } else {
3591 if (ParseIdentifier(Name))
3592 return TokError("expected identifier after '.ifdef'");
3593
3594 Lex();
3595
3596 MCSymbol *Sym = getContext().LookupSymbol(Name);
3597
3598 if (expect_defined)
3599 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3600 else
3601 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3602 TheCondState.Ignore = !TheCondState.CondMet;
3603 }
3604
3605 return false;
3606}
3607
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003608/// ParseDirectiveElseIf
3609/// ::= .elseif expression
3610bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3611 if (TheCondState.TheCond != AsmCond::IfCond &&
3612 TheCondState.TheCond != AsmCond::ElseIfCond)
3613 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3614 " an .elseif");
3615 TheCondState.TheCond = AsmCond::ElseIfCond;
3616
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003617 bool LastIgnoreState = false;
3618 if (!TheCondStack.empty())
3619 LastIgnoreState = TheCondStack.back().Ignore;
3620 if (LastIgnoreState || TheCondState.CondMet) {
3621 TheCondState.Ignore = true;
3622 EatToEndOfStatement();
3623 }
3624 else {
3625 int64_t ExprValue;
3626 if (ParseAbsoluteExpression(ExprValue))
3627 return true;
3628
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003629 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003630 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003631
Sean Callanan79ed1a82010-01-19 20:22:31 +00003632 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003633 TheCondState.CondMet = ExprValue;
3634 TheCondState.Ignore = !TheCondState.CondMet;
3635 }
3636
3637 return false;
3638}
3639
3640/// ParseDirectiveElse
3641/// ::= .else
3642bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003643 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003644 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003645
Sean Callanan79ed1a82010-01-19 20:22:31 +00003646 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003647
3648 if (TheCondState.TheCond != AsmCond::IfCond &&
3649 TheCondState.TheCond != AsmCond::ElseIfCond)
3650 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3651 ".elseif");
3652 TheCondState.TheCond = AsmCond::ElseCond;
3653 bool LastIgnoreState = false;
3654 if (!TheCondStack.empty())
3655 LastIgnoreState = TheCondStack.back().Ignore;
3656 if (LastIgnoreState || TheCondState.CondMet)
3657 TheCondState.Ignore = true;
3658 else
3659 TheCondState.Ignore = false;
3660
3661 return false;
3662}
3663
3664/// ParseDirectiveEndIf
3665/// ::= .endif
3666bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003667 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003668 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003669
Sean Callanan79ed1a82010-01-19 20:22:31 +00003670 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003671
3672 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3673 TheCondStack.empty())
3674 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3675 ".else");
3676 if (!TheCondStack.empty()) {
3677 TheCondState = TheCondStack.back();
3678 TheCondStack.pop_back();
3679 }
3680
3681 return false;
3682}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003683
Eli Bendersky6ee13082013-01-15 22:59:42 +00003684void AsmParser::initializeDirectiveKindMap() {
3685 DirectiveKindMap[".set"] = DK_SET;
3686 DirectiveKindMap[".equ"] = DK_EQU;
3687 DirectiveKindMap[".equiv"] = DK_EQUIV;
3688 DirectiveKindMap[".ascii"] = DK_ASCII;
3689 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3690 DirectiveKindMap[".string"] = DK_STRING;
3691 DirectiveKindMap[".byte"] = DK_BYTE;
3692 DirectiveKindMap[".short"] = DK_SHORT;
3693 DirectiveKindMap[".value"] = DK_VALUE;
3694 DirectiveKindMap[".2byte"] = DK_2BYTE;
3695 DirectiveKindMap[".long"] = DK_LONG;
3696 DirectiveKindMap[".int"] = DK_INT;
3697 DirectiveKindMap[".4byte"] = DK_4BYTE;
3698 DirectiveKindMap[".quad"] = DK_QUAD;
3699 DirectiveKindMap[".8byte"] = DK_8BYTE;
3700 DirectiveKindMap[".single"] = DK_SINGLE;
3701 DirectiveKindMap[".float"] = DK_FLOAT;
3702 DirectiveKindMap[".double"] = DK_DOUBLE;
3703 DirectiveKindMap[".align"] = DK_ALIGN;
3704 DirectiveKindMap[".align32"] = DK_ALIGN32;
3705 DirectiveKindMap[".balign"] = DK_BALIGN;
3706 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3707 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3708 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3709 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3710 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3711 DirectiveKindMap[".org"] = DK_ORG;
3712 DirectiveKindMap[".fill"] = DK_FILL;
3713 DirectiveKindMap[".zero"] = DK_ZERO;
3714 DirectiveKindMap[".extern"] = DK_EXTERN;
3715 DirectiveKindMap[".globl"] = DK_GLOBL;
3716 DirectiveKindMap[".global"] = DK_GLOBAL;
3717 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3718 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3719 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3720 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3721 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3722 DirectiveKindMap[".reference"] = DK_REFERENCE;
3723 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3724 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3725 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3726 DirectiveKindMap[".comm"] = DK_COMM;
3727 DirectiveKindMap[".common"] = DK_COMMON;
3728 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3729 DirectiveKindMap[".abort"] = DK_ABORT;
3730 DirectiveKindMap[".include"] = DK_INCLUDE;
3731 DirectiveKindMap[".incbin"] = DK_INCBIN;
3732 DirectiveKindMap[".code16"] = DK_CODE16;
3733 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3734 DirectiveKindMap[".rept"] = DK_REPT;
3735 DirectiveKindMap[".irp"] = DK_IRP;
3736 DirectiveKindMap[".irpc"] = DK_IRPC;
3737 DirectiveKindMap[".endr"] = DK_ENDR;
3738 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3739 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3740 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3741 DirectiveKindMap[".if"] = DK_IF;
3742 DirectiveKindMap[".ifb"] = DK_IFB;
3743 DirectiveKindMap[".ifnb"] = DK_IFNB;
3744 DirectiveKindMap[".ifc"] = DK_IFC;
3745 DirectiveKindMap[".ifnc"] = DK_IFNC;
3746 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3747 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3748 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3749 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3750 DirectiveKindMap[".else"] = DK_ELSE;
3751 DirectiveKindMap[".endif"] = DK_ENDIF;
3752 DirectiveKindMap[".skip"] = DK_SKIP;
3753 DirectiveKindMap[".space"] = DK_SPACE;
3754 DirectiveKindMap[".file"] = DK_FILE;
3755 DirectiveKindMap[".line"] = DK_LINE;
3756 DirectiveKindMap[".loc"] = DK_LOC;
3757 DirectiveKindMap[".stabs"] = DK_STABS;
3758 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3759 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3760 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3761 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3762 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3763 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3764 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3765 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3766 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3767 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3768 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3769 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3770 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3771 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3772 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3773 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3774 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3775 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3776 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3777 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3778 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3779 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3780 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3781 DirectiveKindMap[".macro"] = DK_MACRO;
3782 DirectiveKindMap[".endm"] = DK_ENDM;
3783 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3784 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003785}
3786
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003787
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003788MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003789 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003790
Rafael Espindola761cb062012-06-03 23:57:14 +00003791 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003792 for (;;) {
3793 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003794 if (getLexer().is(AsmToken::Eof)) {
3795 Error(DirectiveLoc, "no matching '.endr' in definition");
3796 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003797 }
3798
Rafael Espindola761cb062012-06-03 23:57:14 +00003799 if (Lexer.is(AsmToken::Identifier) &&
3800 (getTok().getIdentifier() == ".rept")) {
3801 ++NestLevel;
3802 }
3803
3804 // Otherwise, check whether we have reached the .endr.
3805 if (Lexer.is(AsmToken::Identifier) &&
3806 getTok().getIdentifier() == ".endr") {
3807 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003808 EndToken = getTok();
3809 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003810 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3811 TokError("unexpected token in '.endr' directive");
3812 return 0;
3813 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003814 break;
3815 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003816 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003817 }
3818
Rafael Espindola761cb062012-06-03 23:57:14 +00003819 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003820 EatToEndOfStatement();
3821 }
3822
3823 const char *BodyStart = StartToken.getLoc().getPointer();
3824 const char *BodyEnd = EndToken.getLoc().getPointer();
3825 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3826
Rafael Espindola761cb062012-06-03 23:57:14 +00003827 // We Are Anonymous.
3828 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003829 MCAsmMacroParameters Parameters;
3830 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003831}
3832
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003833void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003834 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003835 OS << ".endr\n";
3836
3837 MemoryBuffer *Instantiation =
3838 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3839
Rafael Espindola761cb062012-06-03 23:57:14 +00003840 // Create the macro instantiation object and add to the current macro
3841 // instantiation stack.
3842 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003843 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003844 getTok().getLoc(),
3845 Instantiation);
3846 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003847
Rafael Espindola761cb062012-06-03 23:57:14 +00003848 // Jump to the macro instantiation and prime the lexer.
3849 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3850 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3851 Lex();
3852}
3853
3854bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3855 int64_t Count;
3856 if (ParseAbsoluteExpression(Count))
3857 return TokError("unexpected token in '.rept' directive");
3858
3859 if (Count < 0)
3860 return TokError("Count is negative");
3861
3862 if (Lexer.isNot(AsmToken::EndOfStatement))
3863 return TokError("unexpected token in '.rept' directive");
3864
3865 // Eat the end of statement.
3866 Lex();
3867
3868 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003869 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003870 if (!M)
3871 return true;
3872
3873 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3874 // to hold the macro body with substitutions.
3875 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003876 MCAsmMacroParameters Parameters;
3877 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003878 raw_svector_ostream OS(Buf);
3879 while (Count--) {
3880 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3881 return true;
3882 }
3883 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003884
3885 return false;
3886}
3887
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003888/// ParseDirectiveIrp
3889/// ::= .irp symbol,values
3890bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003891 MCAsmMacroParameters Parameters;
3892 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003893
Preston Gurd6c9176a2012-09-19 20:29:04 +00003894 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003895 return TokError("expected identifier in '.irp' directive");
3896
3897 Parameters.push_back(Parameter);
3898
3899 if (Lexer.isNot(AsmToken::Comma))
3900 return TokError("expected comma in '.irp' directive");
3901
3902 Lex();
3903
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003904 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003905 if (ParseMacroArguments(0, A))
3906 return true;
3907
3908 // Eat the end of statement.
3909 Lex();
3910
3911 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003912 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003913 if (!M)
3914 return true;
3915
3916 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3917 // to hold the macro body with substitutions.
3918 SmallString<256> Buf;
3919 raw_svector_ostream OS(Buf);
3920
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003921 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3922 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003923 Args.push_back(*i);
3924
3925 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3926 return true;
3927 }
3928
3929 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3930
3931 return false;
3932}
3933
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003934/// ParseDirectiveIrpc
3935/// ::= .irpc symbol,values
3936bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003937 MCAsmMacroParameters Parameters;
3938 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003939
Preston Gurd6c9176a2012-09-19 20:29:04 +00003940 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003941 return TokError("expected identifier in '.irpc' directive");
3942
3943 Parameters.push_back(Parameter);
3944
3945 if (Lexer.isNot(AsmToken::Comma))
3946 return TokError("expected comma in '.irpc' directive");
3947
3948 Lex();
3949
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003950 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003951 if (ParseMacroArguments(0, A))
3952 return true;
3953
3954 if (A.size() != 1 || A.front().size() != 1)
3955 return TokError("unexpected token in '.irpc' directive");
3956
3957 // Eat the end of statement.
3958 Lex();
3959
3960 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003961 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003962 if (!M)
3963 return true;
3964
3965 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3966 // to hold the macro body with substitutions.
3967 SmallString<256> Buf;
3968 raw_svector_ostream OS(Buf);
3969
3970 StringRef Values = A.front().front().getString();
3971 std::size_t I, End = Values.size();
3972 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003973 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003974 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3975
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003976 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003977 Args.push_back(Arg);
3978
3979 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3980 return true;
3981 }
3982
3983 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3984
3985 return false;
3986}
3987
Rafael Espindola761cb062012-06-03 23:57:14 +00003988bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3989 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003990 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003991
3992 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003993 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003994 assert(getLexer().is(AsmToken::EndOfStatement));
3995
Rafael Espindola761cb062012-06-03 23:57:14 +00003996 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003997 return false;
3998}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003999
Chad Rosier469b1442013-02-12 21:33:51 +00004000bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004001 const MCExpr *Value;
4002 SMLoc ExprLoc = getLexer().getLoc();
4003 if (ParseExpression(Value))
4004 return true;
4005 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4006 if (!MCE)
4007 return Error(ExprLoc, "unexpected expression in _emit");
4008 uint64_t IntValue = MCE->getValue();
4009 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4010 return Error(ExprLoc, "literal value out of range for directive");
4011
Chad Rosier469b1442013-02-12 21:33:51 +00004012 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4013 return false;
4014}
4015
4016bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4017 const MCExpr *Value;
4018 SMLoc ExprLoc = getLexer().getLoc();
4019 if (ParseExpression(Value))
4020 return true;
4021 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4022 if (!MCE)
4023 return Error(ExprLoc, "unexpected expression in align");
4024 uint64_t IntValue = MCE->getValue();
4025 if (!isPowerOf2_64(IntValue))
4026 return Error(ExprLoc, "literal value not a power of two greater then zero");
4027
4028 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004029 return false;
4030}
4031
Chad Rosierb1953982013-02-13 01:03:13 +00004032bool AsmStringSort (AsmRewrite A, AsmRewrite B) {
4033 return A.Loc.getPointer() < B.Loc.getPointer();
4034}
4035
Chad Rosierb1f8c132012-10-18 15:49:34 +00004036bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4037 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004038 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00004039 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00004040 SmallVectorImpl<std::string> &Clobbers,
4041 const MCInstrInfo *MII,
4042 const MCInstPrinter *IP,
4043 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004044 SmallVector<void *, 4> InputDecls;
4045 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004046 SmallVector<bool, 4> InputDeclsAddressOf;
4047 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004048 SmallVector<std::string, 4> InputConstraints;
4049 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004050 std::set<std::string> ClobberRegs;
4051
Chad Rosier4e472d22012-10-20 01:02:45 +00004052 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004053
4054 // Prime the lexer.
4055 Lex();
4056
4057 // While we have input, parse each statement.
4058 unsigned InputIdx = 0;
4059 unsigned OutputIdx = 0;
4060 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004061 ParseStatementInfo Info(&AsmStrRewrites);
4062 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004063 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004064
Chad Rosier57498012012-12-12 22:45:52 +00004065 if (Info.ParseError)
4066 return true;
4067
Eli Friedman2128aae2012-10-22 23:58:19 +00004068 if (Info.Opcode != ~0U) {
4069 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004070
4071 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00004072 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4073 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004074
4075 // Immediate.
4076 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00004077 if (Operand->needAsmRewrite())
4078 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
4079 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004080 continue;
4081 }
4082
4083 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00004084 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004085 unsigned NumDefs = Desc.getNumDefs();
4086 // Clobber.
4087 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
4088 std::string Reg;
4089 raw_string_ostream OS(Reg);
4090 IP->printRegName(OS, Operand->getReg());
4091 ClobberRegs.insert(StringRef(OS.str()));
4092 }
4093 continue;
4094 }
4095
4096 // Expr/Input or Output.
Chad Rosierc1ec2072013-01-10 22:10:27 +00004097 bool IsVarDecl;
Chad Rosier505bca32013-01-17 19:21:48 +00004098 unsigned Length, Size, Type;
Chad Rosier32989592012-10-18 20:27:15 +00004099 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosier505bca32013-01-17 19:21:48 +00004100 Length, Size, Type, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004101 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004102 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00004103 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00004104 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00004105 Operand->getStartLoc(),
4106 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004107 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004108 if (isOutput) {
4109 std::string Constraint = "=";
4110 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004111 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00004112 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00004113 Constraint += Operand->getConstraint().str();
4114 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00004115 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004116 Operand->getStartLoc(),
4117 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004118 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004119 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00004120 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00004121 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00004122 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00004123 Operand->getStartLoc(),
4124 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004125 }
4126 }
4127 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004128 }
4129 }
4130
4131 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004132 NumOutputs = OutputDecls.size();
4133 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004134
4135 // Set the unique clobbers.
4136 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4137 E = ClobberRegs.end(); I != E; ++I)
4138 Clobbers.push_back(*I);
4139
4140 // Merge the various outputs and inputs. Output are expected first.
4141 if (NumOutputs || NumInputs) {
4142 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004143 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004144 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004145 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004146 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004147 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004148 }
4149 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004150 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004151 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004152 }
4153 }
4154
4155 // Build the IR assembly string.
4156 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004157 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004158 raw_string_ostream OS(AsmStringIR);
4159 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosierb1953982013-02-13 01:03:13 +00004160 std::sort (AsmStrRewrites.begin(), AsmStrRewrites.end(), AsmStringSort);
Chad Rosier4e472d22012-10-20 01:02:45 +00004161 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004162 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4163 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004164
Chad Rosier469b1442013-02-12 21:33:51 +00004165 unsigned AdditionalSkip = 0;
Chad Rosier4e472d22012-10-20 01:02:45 +00004166 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004167
4168 // Emit everything up to the immediate/expression. If the previous rewrite
4169 // was a size directive, then this has already been done.
4170 if (PrevKind != AOK_SizeDirective)
4171 OS << StringRef(Start, Loc - Start);
4172 PrevKind = Kind;
4173
Chad Rosier5a719fc2012-10-23 17:43:43 +00004174 // Skip the original expression.
4175 if (Kind == AOK_Skip) {
4176 Start = Loc + (*I).Len;
4177 continue;
4178 }
4179
Chad Rosierb1f8c132012-10-18 15:49:34 +00004180 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004181 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004182 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004183 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004184 OS << Twine("$$");
4185 OS << (*I).Val;
4186 break;
4187 case AOK_ImmPrefix:
4188 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004189 break;
4190 case AOK_Input:
4191 OS << '$';
4192 OS << InputIdx++;
4193 break;
4194 case AOK_Output:
4195 OS << '$';
4196 OS << OutputIdx++;
4197 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004198 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004199 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004200 default: break;
4201 case 8: OS << "byte ptr "; break;
4202 case 16: OS << "word ptr "; break;
4203 case 32: OS << "dword ptr "; break;
4204 case 64: OS << "qword ptr "; break;
4205 case 80: OS << "xword ptr "; break;
4206 case 128: OS << "xmmword ptr "; break;
4207 case 256: OS << "ymmword ptr "; break;
4208 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004209 break;
4210 case AOK_Emit:
4211 OS << ".byte";
4212 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004213 case AOK_Align: {
4214 unsigned Val = (*I).Val;
4215 OS << ".align " << Val;
4216
4217 // Skip the original immediate.
4218 assert (Val < 10 && "Expected alignment less then 2^10.");
4219 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4220 break;
4221 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004222 case AOK_DotOperator:
4223 OS << (*I).Val;
4224 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004225 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004226
Chad Rosierb1f8c132012-10-18 15:49:34 +00004227 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004228 if (Kind != AOK_SizeDirective)
Chad Rosier469b1442013-02-12 21:33:51 +00004229 Start = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004230 }
4231
4232 // Emit the remainder of the asm string.
4233 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4234 if (Start != AsmEnd)
4235 OS << StringRef(Start, AsmEnd - Start);
4236
4237 AsmString = OS.str();
4238 return false;
4239}
4240
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004241/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004242MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004243 MCContext &C, MCStreamer &Out,
4244 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004245 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004246}