blob: f7798c511f9eb57e0f244758bb6a49188aea6182 [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
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
50
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000053/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000054typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000055typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000056typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000057typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000058
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000059struct Macro {
60 StringRef Name;
61 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000062 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000063
64public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000065 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000066 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000067};
68
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000069/// \brief Helper class for storing information about an active macro
70/// instantiation.
71struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
74
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
77
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
80
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000081 /// The buffer where parsing should resume upon instantiation completion.
82 int ExitBuffer;
83
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000084 /// The location where parsing should resume upon instantiation completion.
85 SMLoc ExitLoc;
86
87public:
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000088 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000089 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000090};
91
Chad Rosier6a020a72012-10-25 20:41:34 +000092//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000093struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
96
97 /// Opcode - The opcode from the last parsed instruction.
98 unsigned Opcode;
99
Chad Rosier57498012012-12-12 22:45:52 +0000100 /// Error - Was there an error parsing the inline assembly?
101 bool ParseError;
102
Eli Friedman2128aae2012-10-22 23:58:19 +0000103 SmallVectorImpl<AsmRewrite> *AsmRewrites;
104
Chad Rosier57498012012-12-12 22:45:52 +0000105 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000107 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000108
109 ~ParseStatementInfo() {
110 // Free any parsed operands.
111 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
112 delete ParsedOperands[i];
113 ParsedOperands.clear();
114 }
115};
116
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000117/// \brief The concrete assembly parser instance.
118class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000119 friend class GenericAsmParser;
120
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 *GenericParser;
132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
141 /// DirectiveMap - This is a table handlers for directives. Each handler is
142 /// invoked after the directive identifier is read and is responsible for
143 /// parsing and validating the rest of the directive. The handler is passed
144 /// in the directive name and the location of the directive keyword.
145 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000146
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000147 /// MacroMap - Map of currently defined macros.
148 StringMap<Macro*> MacroMap;
149
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000150 /// ActiveMacros - Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
152
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabled : 1;
155
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
158
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
162 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000163 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000164
Devang Patel0db58bf2012-01-31 18:14:05 +0000165 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
166 unsigned AssemblerDialect;
167
Preston Gurd7b6f2032012-09-19 20:36:12 +0000168 /// IsDarwin - is Darwin compatibility enabled?
169 bool IsDarwin;
170
Chad Rosier8f138d12012-10-15 17:19:13 +0000171 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000172 bool ParsingInlineAsm;
173
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000174public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000175 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000176 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000177 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178
179 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
180
Craig Topper345d16d2012-08-29 05:48:09 +0000181 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
182 StringRef Directive,
183 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000184 DirectiveMap[Directive] = std::make_pair(Object, Handler);
185 }
186
187public:
188 /// @name MCAsmParser Interface
189 /// {
190
191 virtual SourceMgr &getSourceManager() { return SrcMgr; }
192 virtual MCAsmLexer &getLexer() { return Lexer; }
193 virtual MCContext &getContext() { return Ctx; }
194 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000195 virtual unsigned getAssemblerDialect() {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
198 else
199 return AssemblerDialect;
200 }
201 virtual void setAssemblerDialect(unsigned i) {
202 AssemblerDialect = i;
203 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000204
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000205 virtual bool Warning(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual bool Error(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Craig Topper345d16d2012-08-29 05:48:09 +0000210 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000211
Chad Rosier84125ca2012-10-13 00:26:04 +0000212 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000213 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214
215 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
216 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000217 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000218 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000219 SmallVectorImpl<std::string> &Clobbers,
220 const MCInstrInfo *MII,
221 const MCInstPrinter *IP,
222 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000223
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000224 bool ParseExpression(const MCExpr *&Res);
225 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
227 virtual bool ParseAbsoluteExpression(int64_t &Res);
228
229 /// }
230
231private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000232 void CheckForValidSection();
233
Eli Friedman2128aae2012-10-22 23:58:19 +0000234 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000235 void EatToEndOfLine();
236 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000237
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000238 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000240 const MacroParameters &Parameters,
241 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000242 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000243 void HandleMacroExit();
244
245 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000246 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000247 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
248 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000249 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000250 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000251
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000252 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
253 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000254 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
255 /// This returns true on failure.
256 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000257
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000258 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000259 /// current token is not set; clients should ensure Lex() is called
260 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000261 ///
262 /// \param InBuffer If not -1, should be the known buffer id that contains the
263 /// location.
264 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000265
Craig Topper345d16d2012-08-29 05:48:09 +0000266 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000267
Preston Gurd7b6f2032012-09-19 20:36:12 +0000268 bool ParseMacroArgument(MacroArgument &MA,
269 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000270 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000271
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000272 /// \brief Parse up to the end of statement and a return the contents from the
273 /// current token until the end of the statement; the current token on exit
274 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000275 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000276
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000277 /// \brief Parse until the end of a statement or a comma is encountered,
278 /// return the contents from the current token up to the end or comma.
279 StringRef ParseStringToComma();
280
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000281 bool ParseAssignment(StringRef Name, bool allow_redef,
282 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283
284 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
286 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000287 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000288
289 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000290 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000291 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000292
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000293 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000294
295 // ".ascii", ".asciiz", ".string"
296 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000297 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000298 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000299 bool ParseDirectiveFill(); // ".fill"
300 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000301 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000302 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000303 bool ParseDirectiveOrg(); // ".org"
304 // ".align{,32}", ".p2align{,w,l}"
305 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
306
307 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
308 /// accepts a single symbol (which should be a label or an external).
309 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000310
311 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
312
313 bool ParseDirectiveAbort(); // ".abort"
314 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000315 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000316
317 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000318 // ".ifb" or ".ifnb", depending on ExpectBlank.
319 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000320 // ".ifc" or ".ifnc", depending on ExpectEqual.
321 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000322 // ".ifdef" or ".ifndef", depending on expect_defined
323 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
325 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
326 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
327
328 /// ParseEscapedString - Parse the current token as a string which may include
329 /// escaped characters and return the string contents.
330 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000331
332 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
333 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000334
Rafael Espindola761cb062012-06-03 23:57:14 +0000335 // Macro-like directives
336 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
337 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
338 raw_svector_ostream &OS);
339 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000340 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000341 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000342 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000343
Eli Friedman2128aae2012-10-22 23:58:19 +0000344 // "_emit"
345 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000346};
347
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000348/// \brief Generic implementations of directive handling, etc. which is shared
349/// (or the default, at least) for all assembler parser.
350class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000351 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
352 void AddDirectiveHandler(StringRef Directive) {
353 getParser().AddDirectiveHandler(this, Directive,
354 HandleDirective<GenericAsmParser, Handler>);
355 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000356public:
357 GenericAsmParser() {}
358
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000359 AsmParser &getParser() {
360 return (AsmParser&) this->MCAsmParserExtension::getParser();
361 }
362
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000363 virtual void Initialize(MCAsmParser &Parser) {
364 // Call the base implementation.
365 this->MCAsmParserExtension::Initialize(Parser);
366
367 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000368 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
369 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
370 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000371 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000372
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000373 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000374 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
375 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000376 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
377 ".cfi_startproc");
378 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
379 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000380 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
381 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000382 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
383 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
385 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
387 ".cfi_def_cfa_register");
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
389 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
391 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000392 AddDirectiveHandler<
393 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
394 AddDirectiveHandler<
395 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000396 AddDirectiveHandler<
397 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
398 AddDirectiveHandler<
399 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000400 AddDirectiveHandler<
401 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000402 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000403 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
404 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000405 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000406 AddDirectiveHandler<
407 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000408 AddDirectiveHandler<
409 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000410 AddDirectiveHandler<
411 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000412
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000413 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000414 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
415 ".macros_on");
416 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
417 ".macros_off");
418 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
419 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
420 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000421 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000422
423 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
424 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000425 }
426
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000427 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
428
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000429 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
430 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
431 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000432 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000433 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000434 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
435 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000436 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000437 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000438 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000439 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
440 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000441 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000442 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000443 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
444 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000445 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000446 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000447 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000448 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000449 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000450 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000451
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000452 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000453 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
454 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000455 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000456
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000457 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000458};
459
460}
461
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000462namespace llvm {
463
464extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000465extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000466extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000467
468}
469
Chris Lattneraaec2052010-01-19 19:46:13 +0000470enum { DEFAULT_ADDRSPACE = 0 };
471
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000472AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000473 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000474 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000475 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000476 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000477 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000478 // Save the old handler.
479 SavedDiagHandler = SrcMgr.getDiagHandler();
480 SavedDiagContext = SrcMgr.getDiagContext();
481 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000482 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000483 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000484
485 // Initialize the generic parser.
486 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000487
488 // Initialize the platform / file format parser.
489 //
490 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
491 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000492 if (_MAI.hasMicrosoftFastStdCallMangling()) {
493 PlatformParser = createCOFFAsmParser();
494 PlatformParser->Initialize(*this);
495 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000496 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000497 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000498 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000499 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000500 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000501 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000502 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000503}
504
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000505AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000506 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
507
508 // Destroy any macros.
509 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
510 ie = MacroMap.end(); it != ie; ++it)
511 delete it->getValue();
512
Daniel Dunbare4749702010-07-12 18:12:02 +0000513 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000514 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000515}
516
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000517void AsmParser::PrintMacroInstantiations() {
518 // Print the active macro instantiation stack.
519 for (std::vector<MacroInstantiation*>::const_reverse_iterator
520 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000521 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
522 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000523}
524
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000525bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000526 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000527 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000528 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000529 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000530 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000531}
532
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000533bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000534 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000535 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000536 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000537 return true;
538}
539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000541 std::string IncludedFile;
542 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 if (NewBuf == -1)
544 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000545
Sean Callananfd0b0282010-01-21 00:19:58 +0000546 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000547
Sean Callananfd0b0282010-01-21 00:19:58 +0000548 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000549
Sean Callananfd0b0282010-01-21 00:19:58 +0000550 return false;
551}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000552
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000553/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000554/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000555/// returns true on failure.
556bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
557 std::string IncludedFile;
558 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
559 if (NewBuf == -1)
560 return true;
561
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000562 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000563 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
564 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000565 return false;
566}
567
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000568void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
569 if (InBuffer != -1) {
570 CurBuffer = InBuffer;
571 } else {
572 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
573 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000574 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
575}
576
Sean Callananfd0b0282010-01-21 00:19:58 +0000577const AsmToken &AsmParser::Lex() {
578 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 if (tok->is(AsmToken::Eof)) {
581 // If this is the end of an included file, pop the parent file off the
582 // include stack.
583 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
584 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000585 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000586 tok = &Lexer.Lex();
587 }
588 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000589
Sean Callananfd0b0282010-01-21 00:19:58 +0000590 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000591 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000592
Sean Callananfd0b0282010-01-21 00:19:58 +0000593 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000594}
595
Chris Lattner79180e22010-04-05 23:15:42 +0000596bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000597 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000598 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000599 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000600
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000601 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000602 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000603
604 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000605 AsmCond StartingCondState = TheCondState;
606
Kevin Enderby613b7572011-11-01 22:27:22 +0000607 // If we are generating dwarf for assembly source files save the initial text
608 // section and generate a .file directive.
609 if (getContext().getGenDwarfForAssembly()) {
610 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000611 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
612 getStreamer().EmitLabel(SectionStartSym);
613 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000614 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
615 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
616 }
617
Chris Lattnerb717fb02009-07-02 21:53:43 +0000618 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000619 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000620 ParseStatementInfo Info;
621 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000622
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000623 // We had an error, validate that one was emitted and recover by skipping to
624 // the next line.
625 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000626 EatToEndOfStatement();
627 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000628
629 if (TheCondState.TheCond != StartingCondState.TheCond ||
630 TheCondState.Ignore != StartingCondState.Ignore)
631 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000632
633 // Check to see there are no empty DwarfFile slots.
634 const std::vector<MCDwarfFile *> &MCDwarfFiles =
635 getContext().getMCDwarfFiles();
636 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000637 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000638 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000639 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000640
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000641 // Check to see that all assembler local symbols were actually defined.
642 // Targets that don't do subsections via symbols may not want this, though,
643 // so conservatively exclude them. Only do this if we're finalizing, though,
644 // as otherwise we won't necessarilly have seen everything yet.
645 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
646 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
647 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
648 e = Symbols.end();
649 i != e; ++i) {
650 MCSymbol *Sym = i->getValue();
651 // Variable symbols may not be marked as defined, so check those
652 // explicitly. If we know it's a variable, we have a definition for
653 // the purposes of this check.
654 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
655 // FIXME: We would really like to refer back to where the symbol was
656 // first referenced for a source location. We need to add something
657 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000658 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
659 "assembler local symbol '" + Sym->getName() +
660 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000661 }
662 }
663
664
Chris Lattner79180e22010-04-05 23:15:42 +0000665 // Finalize the output stream if there are no errors and if the client wants
666 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000667 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000668 Out.Finish();
669
Chris Lattnerb717fb02009-07-02 21:53:43 +0000670 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000671}
672
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000673void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000674 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000675 TokError("expected section directive before assembly directive");
676 Out.SwitchSection(Ctx.getMachOSection(
677 "__TEXT", "__text",
678 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
679 0, SectionKind::getText()));
680 }
681}
682
Chris Lattner2cf5f142009-06-22 01:29:09 +0000683/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
684void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000685 while (Lexer.isNot(AsmToken::EndOfStatement) &&
686 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000687 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000688
Chris Lattner2cf5f142009-06-22 01:29:09 +0000689 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000690 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000691 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000692}
693
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000694StringRef AsmParser::ParseStringToEndOfStatement() {
695 const char *Start = getTok().getLoc().getPointer();
696
697 while (Lexer.isNot(AsmToken::EndOfStatement) &&
698 Lexer.isNot(AsmToken::Eof))
699 Lex();
700
701 const char *End = getTok().getLoc().getPointer();
702 return StringRef(Start, End - Start);
703}
Chris Lattnerc4193832009-06-22 05:51:26 +0000704
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000705StringRef AsmParser::ParseStringToComma() {
706 const char *Start = getTok().getLoc().getPointer();
707
708 while (Lexer.isNot(AsmToken::EndOfStatement) &&
709 Lexer.isNot(AsmToken::Comma) &&
710 Lexer.isNot(AsmToken::Eof))
711 Lex();
712
713 const char *End = getTok().getLoc().getPointer();
714 return StringRef(Start, End - Start);
715}
716
Chris Lattner74ec1a32009-06-22 06:32:03 +0000717/// ParseParenExpr - Parse a paren expression and return it.
718/// NOTE: This assumes the leading '(' has already been consumed.
719///
720/// parenexpr ::= expr)
721///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000722bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000723 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000724 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000725 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000726 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000727 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000728 return false;
729}
Chris Lattnerc4193832009-06-22 05:51:26 +0000730
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000731/// ParseBracketExpr - Parse a bracket expression and return it.
732/// NOTE: This assumes the leading '[' has already been consumed.
733///
734/// bracketexpr ::= expr]
735///
736bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
737 if (ParseExpression(Res)) return true;
738 if (Lexer.isNot(AsmToken::RBrac))
739 return TokError("expected ']' in brackets expression");
740 EndLoc = Lexer.getLoc();
741 Lex();
742 return false;
743}
744
Chris Lattner74ec1a32009-06-22 06:32:03 +0000745/// ParsePrimaryExpr - Parse a primary expression and return it.
746/// primaryexpr ::= (parenexpr
747/// primaryexpr ::= symbol
748/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000749/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000750/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000751bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000752 switch (Lexer.getKind()) {
753 default:
754 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000755 // If we have an error assume that we've already handled it.
756 case AsmToken::Error:
757 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000758 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000759 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000760 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000761 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000762 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000763 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000764 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000765 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000766 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000767 EndLoc = Lexer.getLoc();
768
769 StringRef Identifier;
770 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000771 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000772
Daniel Dunbarfffff912009-10-16 01:34:54 +0000773 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000774 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000775 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000776
777 // Lookup the symbol variant if used.
778 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000779 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000780 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000781 if (Variant == MCSymbolRefExpr::VK_Invalid) {
782 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000783 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000784 }
785 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000786
Daniel Dunbarfffff912009-10-16 01:34:54 +0000787 // If this is an absolute variable reference, substitute it now to preserve
788 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000789 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000790 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000791 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000792
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000793 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000794 return false;
795 }
796
797 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000798 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000799 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000800 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000801 case AsmToken::Integer: {
802 SMLoc Loc = getTok().getLoc();
803 int64_t IntVal = getTok().getIntVal();
804 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000805 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000806 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000807 // Look for 'b' or 'f' following an Integer as a directional label
808 if (Lexer.getKind() == AsmToken::Identifier) {
809 StringRef IDVal = getTok().getString();
810 if (IDVal == "f" || IDVal == "b"){
811 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
812 IDVal == "f" ? 1 : 0);
813 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
814 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000815 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000816 return Error(Loc, "invalid reference to undefined symbol");
817 EndLoc = Lexer.getLoc();
818 Lex(); // Eat identifier.
819 }
820 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000821 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000822 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000823 case AsmToken::Real: {
824 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000825 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000826 Res = MCConstantExpr::Create(IntVal, getContext());
827 Lex(); // Eat token.
828 return false;
829 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000830 case AsmToken::Dot: {
831 // This is a '.' reference, which references the current PC. Emit a
832 // temporary label to the streamer and refer to it.
833 MCSymbol *Sym = Ctx.CreateTempSymbol();
834 Out.EmitLabel(Sym);
835 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
836 EndLoc = Lexer.getLoc();
837 Lex(); // Eat identifier.
838 return false;
839 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000840 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000841 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000842 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000843 case AsmToken::LBrac:
844 if (!PlatformParser->HasBracketExpressions())
845 return TokError("brackets expression not supported on this target");
846 Lex(); // Eat the '['.
847 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000848 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000849 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000850 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000851 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000852 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000853 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000854 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000855 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000856 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000857 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000858 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000859 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000860 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000861 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000862 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000863 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000864 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000865 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000866 }
867}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000868
Chris Lattnerb4307b32010-01-15 19:28:38 +0000869bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000870 SMLoc EndLoc;
871 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000872}
873
Daniel Dunbarcceba832010-09-17 02:47:07 +0000874const MCExpr *
875AsmParser::ApplyModifierToExpr(const MCExpr *E,
876 MCSymbolRefExpr::VariantKind Variant) {
877 // Recurse over the given expression, rebuilding it to apply the given variant
878 // if there is exactly one symbol.
879 switch (E->getKind()) {
880 case MCExpr::Target:
881 case MCExpr::Constant:
882 return 0;
883
884 case MCExpr::SymbolRef: {
885 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
886
887 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
888 TokError("invalid variant on expression '" +
889 getTok().getIdentifier() + "' (already modified)");
890 return E;
891 }
892
893 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
894 }
895
896 case MCExpr::Unary: {
897 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
898 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
899 if (!Sub)
900 return 0;
901 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
902 }
903
904 case MCExpr::Binary: {
905 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
906 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
907 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
908
909 if (!LHS && !RHS)
910 return 0;
911
912 if (!LHS) LHS = BE->getLHS();
913 if (!RHS) RHS = BE->getRHS();
914
915 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
916 }
917 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000918
Craig Topper85814382012-02-07 05:05:23 +0000919 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000920}
921
Chris Lattner74ec1a32009-06-22 06:32:03 +0000922/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000923///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000924/// expr ::= expr &&,|| expr -> lowest.
925/// expr ::= expr |,^,&,! expr
926/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
927/// expr ::= expr <<,>> expr
928/// expr ::= expr +,- expr
929/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000930/// expr ::= primaryexpr
931///
Chris Lattner54482b42010-01-15 19:39:23 +0000932bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000933 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000934 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000935 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
936 return true;
937
Daniel Dunbarcceba832010-09-17 02:47:07 +0000938 // As a special case, we support 'a op b @ modifier' by rewriting the
939 // expression to include the modifier. This is inefficient, but in general we
940 // expect users to use 'a@modifier op b'.
941 if (Lexer.getKind() == AsmToken::At) {
942 Lex();
943
944 if (Lexer.isNot(AsmToken::Identifier))
945 return TokError("unexpected symbol modifier following '@'");
946
947 MCSymbolRefExpr::VariantKind Variant =
948 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
949 if (Variant == MCSymbolRefExpr::VK_Invalid)
950 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
951
952 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
953 if (!ModifiedRes) {
954 return TokError("invalid modifier '" + getTok().getIdentifier() +
955 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000956 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000957
Daniel Dunbarcceba832010-09-17 02:47:07 +0000958 Res = ModifiedRes;
959 Lex();
960 }
961
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000962 // Try to constant fold it up front, if possible.
963 int64_t Value;
964 if (Res->EvaluateAsAbsolute(Value))
965 Res = MCConstantExpr::Create(Value, getContext());
966
967 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000968}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000969
Chris Lattnerb4307b32010-01-15 19:28:38 +0000970bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000971 Res = 0;
972 return ParseParenExpr(Res, EndLoc) ||
973 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000974}
975
Daniel Dunbar475839e2009-06-29 20:37:27 +0000976bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000977 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000978
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000979 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000980 if (ParseExpression(Expr))
981 return true;
982
Daniel Dunbare00b0112009-10-16 01:57:52 +0000983 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000984 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000985
986 return false;
987}
988
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000989static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000990 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000991 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000992 default:
993 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994
Jim Grosbachfbe16812011-08-20 16:24:13 +0000995 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000996 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000997 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000998 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000999 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001001 return 1;
1002
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001003
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001004 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001005 //
1006 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001007 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001008 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001009 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001012 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001013 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001014 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001015 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001016
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001017 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001018 case AsmToken::EqualEqual:
1019 Kind = MCBinaryExpr::EQ;
1020 return 3;
1021 case AsmToken::ExclaimEqual:
1022 case AsmToken::LessGreater:
1023 Kind = MCBinaryExpr::NE;
1024 return 3;
1025 case AsmToken::Less:
1026 Kind = MCBinaryExpr::LT;
1027 return 3;
1028 case AsmToken::LessEqual:
1029 Kind = MCBinaryExpr::LTE;
1030 return 3;
1031 case AsmToken::Greater:
1032 Kind = MCBinaryExpr::GT;
1033 return 3;
1034 case AsmToken::GreaterEqual:
1035 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001036 return 3;
1037
Jim Grosbachfbe16812011-08-20 16:24:13 +00001038 // Intermediate Precedence: <<, >>
1039 case AsmToken::LessLess:
1040 Kind = MCBinaryExpr::Shl;
1041 return 4;
1042 case AsmToken::GreaterGreater:
1043 Kind = MCBinaryExpr::Shr;
1044 return 4;
1045
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001046 // High Intermediate Precedence: +, -
1047 case AsmToken::Plus:
1048 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001049 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001050 case AsmToken::Minus:
1051 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001053
Jim Grosbachfbe16812011-08-20 16:24:13 +00001054 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001055 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001056 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001058 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001059 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001060 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001061 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001062 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001063 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001064 }
1065}
1066
1067
1068/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1069/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001070bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1071 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001072 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001073 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001074 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001075
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001076 // If the next token is lower precedence than we are allowed to eat, return
1077 // successfully with what we ate already.
1078 if (TokPrec < Precedence)
1079 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001080
Sean Callanan79ed1a82010-01-19 20:22:31 +00001081 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001082
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001083 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001084 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001085 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001086
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001087 // If BinOp binds less tightly with RHS than the operator after RHS, let
1088 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001089 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001090 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001091 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001092 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001093 }
1094
Daniel Dunbar475839e2009-06-29 20:37:27 +00001095 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001096 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001097 }
1098}
1099
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001100/// ParseStatement:
1101/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001102/// ::= Label* Directive ...Operands... EndOfStatement
1103/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001104bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001105 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001106 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001107 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001108 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001109 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001110
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001111 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001112 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001113 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001114 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001115 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001116 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001117 if (Lexer.is(AsmToken::Hash))
1118 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001119
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001120 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001121 if (Lexer.is(AsmToken::Integer)) {
1122 LocalLabelVal = getTok().getIntVal();
1123 if (LocalLabelVal < 0) {
1124 if (!TheCondState.Ignore)
1125 return TokError("unexpected token at start of statement");
1126 IDVal = "";
1127 }
1128 else {
1129 IDVal = getTok().getString();
1130 Lex(); // Consume the integer token to be used as an identifier token.
1131 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001132 if (!TheCondState.Ignore)
1133 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001134 }
1135 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001136
1137 } else if (Lexer.is(AsmToken::Dot)) {
1138 // Treat '.' as a valid identifier in this context.
1139 Lex();
1140 IDVal = ".";
1141
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001142 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001143 if (!TheCondState.Ignore)
1144 return TokError("unexpected token at start of statement");
1145 IDVal = "";
1146 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001147
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001148
Chris Lattner7834fac2010-04-17 18:14:27 +00001149 // Handle conditional assembly here before checking for skipping. We
1150 // have to do this so that .endif isn't skipped in a ".if 0" block for
1151 // example.
1152 if (IDVal == ".if")
1153 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001154 if (IDVal == ".ifb")
1155 return ParseDirectiveIfb(IDLoc, true);
1156 if (IDVal == ".ifnb")
1157 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001158 if (IDVal == ".ifc")
1159 return ParseDirectiveIfc(IDLoc, true);
1160 if (IDVal == ".ifnc")
1161 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001162 if (IDVal == ".ifdef")
1163 return ParseDirectiveIfdef(IDLoc, true);
1164 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1165 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001166 if (IDVal == ".elseif")
1167 return ParseDirectiveElseIf(IDLoc);
1168 if (IDVal == ".else")
1169 return ParseDirectiveElse(IDLoc);
1170 if (IDVal == ".endif")
1171 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001172
Chris Lattner7834fac2010-04-17 18:14:27 +00001173 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001174 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001175 EatToEndOfStatement();
1176 return false;
1177 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001178
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001179 // FIXME: Recurse on local labels?
1180
1181 // See what kind of statement we have.
1182 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001183 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001184 CheckForValidSection();
1185
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001186 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001187 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001188
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001189 // Diagnose attempt to use '.' as a label.
1190 if (IDVal == ".")
1191 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1192
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001193 // Diagnose attempt to use a variable as a label.
1194 //
1195 // FIXME: Diagnostics. Note the location of the definition as a label.
1196 // FIXME: This doesn't diagnose assignment to a symbol which has been
1197 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001198 MCSymbol *Sym;
1199 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001200 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001201 else
1202 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001203 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001204 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001205
Daniel Dunbar959fd882009-08-26 22:13:22 +00001206 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001207 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001208
Kevin Enderby94c2e852011-12-09 18:09:40 +00001209 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001210 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001211 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001212 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1213 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001214
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001215 // Consume any end of statement token, if present, to avoid spurious
1216 // AddBlankLine calls().
1217 if (Lexer.is(AsmToken::EndOfStatement)) {
1218 Lex();
1219 if (Lexer.is(AsmToken::Eof))
1220 return false;
1221 }
1222
Eli Friedman2128aae2012-10-22 23:58:19 +00001223 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001224 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001225
Daniel Dunbar3f872332009-07-28 16:08:33 +00001226 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001227 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001228 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001229
Nico Weber4c4c7322011-01-28 03:04:41 +00001230 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001231
1232 default: // Normal instruction or directive.
1233 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001234 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001235
1236 // If macros are enabled, check to see if this is a macro instantiation.
1237 if (MacrosEnabled)
1238 if (const Macro *M = MacroMap.lookup(IDVal))
1239 return HandleMacroEntry(IDVal, IDLoc, M);
1240
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001241 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001242 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001243
1244 // Target hook for parsing target specific directives.
1245 if (!getTargetParser().ParseDirective(ID))
1246 return false;
1247
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001248 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001249 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001250 return ParseDirectiveSet(IDVal, true);
1251 if (IDVal == ".equiv")
1252 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001253
Daniel Dunbara0d14262009-06-24 23:30:00 +00001254 // Data directives
1255
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001257 return ParseDirectiveAscii(IDVal, false);
1258 if (IDVal == ".asciz" || IDVal == ".string")
1259 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001260
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001261 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001262 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001263 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001264 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001265 if (IDVal == ".value")
1266 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001267 if (IDVal == ".2byte")
1268 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001269 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001270 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001271 if (IDVal == ".int")
1272 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001273 if (IDVal == ".4byte")
1274 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001275 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001276 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001277 if (IDVal == ".8byte")
1278 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001279 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001280 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1281 if (IDVal == ".double")
1282 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001283
Eli Friedman5d68ec22010-07-19 04:17:25 +00001284 if (IDVal == ".align") {
1285 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1286 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1287 }
1288 if (IDVal == ".align32") {
1289 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1290 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1291 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001292 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001293 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001294 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001295 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001296 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001297 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001298 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001299 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001300 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001301 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001303 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1304
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001306 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001307
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001308 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001309 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001310 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001311 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001312 if (IDVal == ".zero")
1313 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001314
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001315 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001316
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001317 if (IDVal == ".extern") {
1318 EatToEndOfStatement(); // .extern is the default, ignore it.
1319 return false;
1320 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001321 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001322 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001323 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001324 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001325 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001326 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001327 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001328 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001329 if (IDVal == ".symbol_resolver")
1330 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001331 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001332 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001333 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001334 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001335 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001336 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001337 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001338 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001339 if (IDVal == ".weak_def_can_be_hidden")
1340 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001341
Hans Wennborg5cc64912011-06-18 13:51:54 +00001342 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001343 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001344 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001345 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001346
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001347 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001348 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001349 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001350 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001351 if (IDVal == ".incbin")
1352 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001353
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001354 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001355 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001356
Rafael Espindola761cb062012-06-03 23:57:14 +00001357 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001358 if (IDVal == ".rept")
1359 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001360 if (IDVal == ".irp")
1361 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001362 if (IDVal == ".irpc")
1363 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001364 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001365 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001366
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001367 // Look up the handler in the handler table.
1368 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1369 DirectiveMap.lookup(IDVal);
1370 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001371 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001372
Kevin Enderby9c656452009-09-10 20:51:44 +00001373
Jim Grosbach686c0182012-05-01 18:38:27 +00001374 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001375 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001376
Eli Friedman2128aae2012-10-22 23:58:19 +00001377 // _emit
1378 if (ParsingInlineAsm && IDVal == "_emit")
1379 return ParseDirectiveEmit(IDLoc, Info);
1380
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001381 CheckForValidSection();
1382
Chris Lattnera7f13542010-05-19 23:34:33 +00001383 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001384 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001385 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001386 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001387
Chad Rosier6a020a72012-10-25 20:41:34 +00001388 ParseInstructionInfo IInfo(Info.AsmRewrites);
1389 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1390 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001391 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001392
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001393 // Dump the parsed representation, if requested.
1394 if (getShowParsedOperands()) {
1395 SmallString<256> Str;
1396 raw_svector_ostream OS(Str);
1397 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001398 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001399 if (i != 0)
1400 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001401 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001402 }
1403 OS << "]";
1404
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001405 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001406 }
1407
Kevin Enderby613b7572011-11-01 22:27:22 +00001408 // If we are generating dwarf for assembly source files and the current
1409 // section is the initial text section then generate a .loc directive for
1410 // the instruction.
1411 if (!HadError && getContext().getGenDwarfForAssembly() &&
1412 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001413
1414 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1415
1416 // If we previously parsed a cpp hash file line comment then make sure the
1417 // current Dwarf File is for the CppHashFilename if not then emit the
1418 // Dwarf File table for it and adjust the line number for the .loc.
1419 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1420 getContext().getMCDwarfFiles();
1421 if (CppHashFilename.size() != 0) {
1422 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1423 CppHashFilename)
1424 getStreamer().EmitDwarfFileDirective(
1425 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1426
Kevin Enderby32c1a822012-11-05 21:55:41 +00001427 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001428 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1429 }
1430
Kevin Enderby613b7572011-11-01 22:27:22 +00001431 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001432 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001433 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001434 StringRef());
1435 }
1436
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001437 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001438 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001439 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001440 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1441 Info.ParsedOperands,
1442 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001443 ParsingInlineAsm);
1444 }
Chris Lattner98986712010-01-14 22:21:20 +00001445
Chris Lattnercbf8a982010-09-11 16:18:25 +00001446 // Don't skip the rest of the line, the instruction parser is responsible for
1447 // that.
1448 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001449}
Chris Lattner9a023f72009-06-24 04:43:34 +00001450
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001451/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1452/// since they may not be able to be tokenized to get to the end of line token.
1453void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001454 if (!Lexer.is(AsmToken::EndOfStatement))
1455 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001456 // Eat EOL.
1457 Lex();
1458}
1459
1460/// ParseCppHashLineFilenameComment as this:
1461/// ::= # number "filename"
1462/// or just as a full line comment if it doesn't have a number and a string.
1463bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1464 Lex(); // Eat the hash token.
1465
1466 if (getLexer().isNot(AsmToken::Integer)) {
1467 // Consume the line since in cases it is not a well-formed line directive,
1468 // as if were simply a full line comment.
1469 EatToEndOfLine();
1470 return false;
1471 }
1472
1473 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001474 Lex();
1475
1476 if (getLexer().isNot(AsmToken::String)) {
1477 EatToEndOfLine();
1478 return false;
1479 }
1480
1481 StringRef Filename = getTok().getString();
1482 // Get rid of the enclosing quotes.
1483 Filename = Filename.substr(1, Filename.size()-2);
1484
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001485 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1486 CppHashLoc = L;
1487 CppHashFilename = Filename;
1488 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001489 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001490
1491 // Ignore any trailing characters, they're just comment.
1492 EatToEndOfLine();
1493 return false;
1494}
1495
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001496/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001497/// for the Filename and LineNo if any in the diagnostic.
1498void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1499 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1500 raw_ostream &OS = errs();
1501
1502 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1503 const SMLoc &DiagLoc = Diag.getLoc();
1504 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1505 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1506
1507 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1508 // before printing the message.
1509 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001510 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001511 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1512 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1513 }
1514
1515 // If we have not parsed a cpp hash line filename comment or the source
1516 // manager changed or buffer changed (like in a nested include) then just
1517 // print the normal diagnostic using its Filename and LineNo.
1518 if (!Parser->CppHashLineNumber ||
1519 &DiagSrcMgr != &Parser->SrcMgr ||
1520 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001521 if (Parser->SavedDiagHandler)
1522 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1523 else
1524 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001525 return;
1526 }
1527
1528 // Use the CppHashFilename and calculate a line number based on the
1529 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1530 // the diagnostic.
1531 const std::string Filename = Parser->CppHashFilename;
1532
1533 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1534 int CppHashLocLineNo =
1535 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1536 int LineNo = Parser->CppHashLineNumber - 1 +
1537 (DiagLocLineNo - CppHashLocLineNo);
1538
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001539 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1540 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001541 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001542 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001543
Benjamin Kramer04a04262011-10-16 10:48:29 +00001544 if (Parser->SavedDiagHandler)
1545 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1546 else
1547 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001548}
1549
Rafael Espindola799aacf2012-08-21 18:29:30 +00001550// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1551// difference being that that function accepts '@' as part of identifiers and
1552// we can't do that. AsmLexer.cpp should probably be changed to handle
1553// '@' as a special case when needed.
1554static bool isIdentifierChar(char c) {
1555 return isalnum(c) || c == '_' || c == '$' || c == '.';
1556}
1557
Rafael Espindola761cb062012-06-03 23:57:14 +00001558bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001559 const MacroParameters &Parameters,
1560 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001561 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001562 unsigned NParameters = Parameters.size();
1563 if (NParameters != 0 && NParameters != A.size())
1564 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001565
Preston Gurd7b6f2032012-09-19 20:36:12 +00001566 // A macro without parameters is handled differently on Darwin:
1567 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001568 while (!Body.empty()) {
1569 // Scan for the next substitution.
1570 std::size_t End = Body.size(), Pos = 0;
1571 for (; Pos != End; ++Pos) {
1572 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001573 if (!NParameters) {
1574 // This macro has no parameters, look for $0, $1, etc.
1575 if (Body[Pos] != '$' || Pos + 1 == End)
1576 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001577
Rafael Espindola65366442011-06-05 02:43:45 +00001578 char Next = Body[Pos + 1];
1579 if (Next == '$' || Next == 'n' || isdigit(Next))
1580 break;
1581 } else {
1582 // This macro has parameters, look for \foo, \bar, etc.
1583 if (Body[Pos] == '\\' && Pos + 1 != End)
1584 break;
1585 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001586 }
1587
1588 // Add the prefix.
1589 OS << Body.slice(0, Pos);
1590
1591 // Check if we reached the end.
1592 if (Pos == End)
1593 break;
1594
Rafael Espindola65366442011-06-05 02:43:45 +00001595 if (!NParameters) {
1596 switch (Body[Pos+1]) {
1597 // $$ => $
1598 case '$':
1599 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001600 break;
1601
Rafael Espindola65366442011-06-05 02:43:45 +00001602 // $n => number of arguments
1603 case 'n':
1604 OS << A.size();
1605 break;
1606
1607 // $[0-9] => argument
1608 default: {
1609 // Missing arguments are ignored.
1610 unsigned Index = Body[Pos+1] - '0';
1611 if (Index >= A.size())
1612 break;
1613
1614 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001615 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001616 ie = A[Index].end(); it != ie; ++it)
1617 OS << it->getString();
1618 break;
1619 }
1620 }
1621 Pos += 2;
1622 } else {
1623 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001624 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001625 ++I;
1626
1627 const char *Begin = Body.data() + Pos +1;
1628 StringRef Argument(Begin, I - (Pos +1));
1629 unsigned Index = 0;
1630 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001631 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001632 break;
1633
Preston Gurd7b6f2032012-09-19 20:36:12 +00001634 if (Index == NParameters) {
1635 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1636 Pos += 3;
1637 else {
1638 OS << '\\' << Argument;
1639 Pos = I;
1640 }
1641 } else {
1642 for (MacroArgument::const_iterator it = A[Index].begin(),
1643 ie = A[Index].end(); it != ie; ++it)
1644 if (it->getKind() == AsmToken::String)
1645 OS << it->getStringContents();
1646 else
1647 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001648
Preston Gurd7b6f2032012-09-19 20:36:12 +00001649 Pos += 1 + Argument.size();
1650 }
Rafael Espindola65366442011-06-05 02:43:45 +00001651 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001652 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001653 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001654 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001655
Rafael Espindola65366442011-06-05 02:43:45 +00001656 return false;
1657}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001658
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001659MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1660 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001661 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001662 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1663 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001664{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001665}
1666
Preston Gurd7b6f2032012-09-19 20:36:12 +00001667static bool IsOperator(AsmToken::TokenKind kind)
1668{
1669 switch (kind)
1670 {
1671 default:
1672 return false;
1673 case AsmToken::Plus:
1674 case AsmToken::Minus:
1675 case AsmToken::Tilde:
1676 case AsmToken::Slash:
1677 case AsmToken::Star:
1678 case AsmToken::Dot:
1679 case AsmToken::Equal:
1680 case AsmToken::EqualEqual:
1681 case AsmToken::Pipe:
1682 case AsmToken::PipePipe:
1683 case AsmToken::Caret:
1684 case AsmToken::Amp:
1685 case AsmToken::AmpAmp:
1686 case AsmToken::Exclaim:
1687 case AsmToken::ExclaimEqual:
1688 case AsmToken::Percent:
1689 case AsmToken::Less:
1690 case AsmToken::LessEqual:
1691 case AsmToken::LessLess:
1692 case AsmToken::LessGreater:
1693 case AsmToken::Greater:
1694 case AsmToken::GreaterEqual:
1695 case AsmToken::GreaterGreater:
1696 return true;
1697 }
1698}
1699
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001700/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1701/// This is used for both default macro parameter values and the
1702/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001703bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1704 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001705 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001706 unsigned AddTokens = 0;
1707
1708 // gas accepts arguments separated by whitespace, except on Darwin
1709 if (!IsDarwin)
1710 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001711
1712 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001713 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1714 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001715 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001716 }
1717
1718 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1719 // Spaces and commas cannot be mixed to delimit parameters
1720 if (ArgumentDelimiter == AsmToken::Eof)
1721 ArgumentDelimiter = AsmToken::Comma;
1722 else if (ArgumentDelimiter != AsmToken::Comma) {
1723 Lexer.setSkipSpace(true);
1724 return TokError("expected ' ' for macro argument separator");
1725 }
1726 break;
1727 }
1728
1729 if (Lexer.is(AsmToken::Space)) {
1730 Lex(); // Eat spaces
1731
1732 // Spaces can delimit parameters, but could also be part an expression.
1733 // If the token after a space is an operator, add the token and the next
1734 // one into this argument
1735 if (ArgumentDelimiter == AsmToken::Space ||
1736 ArgumentDelimiter == AsmToken::Eof) {
1737 if (IsOperator(Lexer.getKind())) {
1738 // Check to see whether the token is used as an operator,
1739 // or part of an identifier
1740 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1741 if (*NextChar == ' ')
1742 AddTokens = 2;
1743 }
1744
1745 if (!AddTokens && ParenLevel == 0) {
1746 if (ArgumentDelimiter == AsmToken::Eof &&
1747 !IsOperator(Lexer.getKind()))
1748 ArgumentDelimiter = AsmToken::Space;
1749 break;
1750 }
1751 }
1752 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001753
1754 // HandleMacroEntry relies on not advancing the lexer here
1755 // to be able to fill in the remaining default parameter values
1756 if (Lexer.is(AsmToken::EndOfStatement))
1757 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001758
1759 // Adjust the current parentheses level.
1760 if (Lexer.is(AsmToken::LParen))
1761 ++ParenLevel;
1762 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1763 --ParenLevel;
1764
1765 // Append the token to the current argument list.
1766 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001767 if (AddTokens)
1768 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001769 Lex();
1770 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001771
1772 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001773 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001774 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001775 return false;
1776}
1777
1778// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001779bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001780 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001781 // Argument delimiter is initially unknown. It will be set by
1782 // ParseMacroArgument()
1783 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001784
1785 // Parse two kinds of macro invocations:
1786 // - macros defined without any parameters accept an arbitrary number of them
1787 // - macros defined with parameters accept at most that many of them
1788 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1789 ++Parameter) {
1790 MacroArgument MA;
1791
Preston Gurd7b6f2032012-09-19 20:36:12 +00001792 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001793 return true;
1794
Preston Gurd6c9176a2012-09-19 20:29:04 +00001795 if (!MA.empty() || !NParameters)
1796 A.push_back(MA);
1797 else if (NParameters) {
1798 if (!M->Parameters[Parameter].second.empty())
1799 A.push_back(M->Parameters[Parameter].second);
1800 }
Jim Grosbach97146442012-07-30 22:44:17 +00001801
Preston Gurd6c9176a2012-09-19 20:29:04 +00001802 // At the end of the statement, fill in remaining arguments that have
1803 // default values. If there aren't any, then the next argument is
1804 // required but missing
1805 if (Lexer.is(AsmToken::EndOfStatement)) {
1806 if (NParameters && Parameter < NParameters - 1) {
1807 if (M->Parameters[Parameter + 1].second.empty())
1808 return TokError("macro argument '" +
1809 Twine(M->Parameters[Parameter + 1].first) +
1810 "' is missing");
1811 else
1812 continue;
1813 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001814 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001815 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001816
1817 if (Lexer.is(AsmToken::Comma))
1818 Lex();
1819 }
1820 return TokError("Too many arguments");
1821}
1822
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001823bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1824 const Macro *M) {
1825 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1826 // this, although we should protect against infinite loops.
1827 if (ActiveMacros.size() == 20)
1828 return TokError("macros cannot be nested more than 20 levels deep");
1829
Rafael Espindola8a403d32012-08-08 14:51:03 +00001830 MacroArguments A;
1831 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001832 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001833
Jim Grosbach97146442012-07-30 22:44:17 +00001834 // Remove any trailing empty arguments. Do this after-the-fact as we have
1835 // to keep empty arguments in the middle of the list or positionality
1836 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001837 while (!A.empty() && A.back().empty())
1838 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001839
Rafael Espindola65366442011-06-05 02:43:45 +00001840 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1841 // to hold the macro body with substitutions.
1842 SmallString<256> Buf;
1843 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001844 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001845
Rafael Espindola8a403d32012-08-08 14:51:03 +00001846 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001847 return true;
1848
Rafael Espindola761cb062012-06-03 23:57:14 +00001849 // We include the .endmacro in the buffer as our queue to exit the macro
1850 // instantiation.
1851 OS << ".endmacro\n";
1852
Rafael Espindola65366442011-06-05 02:43:45 +00001853 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001854 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001855
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001856 // Create the macro instantiation object and add to the current macro
1857 // instantiation stack.
1858 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001859 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001860 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001861 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001862 ActiveMacros.push_back(MI);
1863
1864 // Jump to the macro instantiation and prime the lexer.
1865 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1866 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1867 Lex();
1868
1869 return false;
1870}
1871
1872void AsmParser::HandleMacroExit() {
1873 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001874 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001875 Lex();
1876
1877 // Pop the instantiation entry.
1878 delete ActiveMacros.back();
1879 ActiveMacros.pop_back();
1880}
1881
Rafael Espindolae71cc862012-01-28 05:57:00 +00001882static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001883 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001884 case MCExpr::Binary: {
1885 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1886 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001887 break;
1888 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001889 case MCExpr::Target:
1890 case MCExpr::Constant:
1891 return false;
1892 case MCExpr::SymbolRef: {
1893 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001894 if (S.isVariable())
1895 return IsUsedIn(Sym, S.getVariableValue());
1896 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001897 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001898 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001899 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001900 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001901
1902 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001903}
1904
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001905bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1906 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001907 // FIXME: Use better location, we should use proper tokens.
1908 SMLoc EqualLoc = Lexer.getLoc();
1909
Daniel Dunbar821e3332009-08-31 08:09:28 +00001910 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001911 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001912 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001913
Rafael Espindolae71cc862012-01-28 05:57:00 +00001914 // Note: we don't count b as used in "a = b". This is to allow
1915 // a = b
1916 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001917
Daniel Dunbar3f872332009-07-28 16:08:33 +00001918 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001919 return TokError("unexpected token in assignment");
1920
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001921 // Error on assignment to '.'.
1922 if (Name == ".") {
1923 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1924 "(use '.space' or '.org').)"));
1925 }
1926
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001927 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001928 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001929
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001930 // Validate that the LHS is allowed to be a variable (either it has not been
1931 // used as a symbol, or it is an absolute symbol).
1932 MCSymbol *Sym = getContext().LookupSymbol(Name);
1933 if (Sym) {
1934 // Diagnose assignment to a label.
1935 //
1936 // FIXME: Diagnostics. Note the location of the definition as a label.
1937 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001938 if (IsUsedIn(Sym, Value))
1939 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1940 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001941 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001942 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1943 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001944 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001945 return Error(EqualLoc, "redefinition of '" + Name + "'");
1946 else if (!Sym->isVariable())
1947 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001948 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001949 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1950 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001951
1952 // Don't count these checks as uses.
1953 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001954 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001955 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001956
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001957 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001958
1959 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001960 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001961 if (NoDeadStrip)
1962 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1963
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001964
1965 return false;
1966}
1967
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001968/// ParseIdentifier:
1969/// ::= identifier
1970/// ::= string
1971bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001972 // The assembler has relaxed rules for accepting identifiers, in particular we
1973 // allow things like '.globl $foo', which would normally be separate
1974 // tokens. At this level, we have already lexed so we cannot (currently)
1975 // handle this as a context dependent token, instead we detect adjacent tokens
1976 // and return the combined identifier.
1977 if (Lexer.is(AsmToken::Dollar)) {
1978 SMLoc DollarLoc = getLexer().getLoc();
1979
1980 // Consume the dollar sign, and check for a following identifier.
1981 Lex();
1982 if (Lexer.isNot(AsmToken::Identifier))
1983 return true;
1984
1985 // We have a '$' followed by an identifier, make sure they are adjacent.
1986 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1987 return true;
1988
1989 // Construct the joined identifier and consume the token.
1990 Res = StringRef(DollarLoc.getPointer(),
1991 getTok().getIdentifier().size() + 1);
1992 Lex();
1993 return false;
1994 }
1995
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001996 if (Lexer.isNot(AsmToken::Identifier) &&
1997 Lexer.isNot(AsmToken::String))
1998 return true;
1999
Sean Callanan18b83232010-01-19 21:44:56 +00002000 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002001
Sean Callanan79ed1a82010-01-19 20:22:31 +00002002 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002003
2004 return false;
2005}
2006
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002007/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002008/// ::= .equ identifier ',' expression
2009/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002010/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002011bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002012 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002013
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002014 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002015 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002016
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002017 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002018 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002019 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002020
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002021 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002022}
2023
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002024bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002025 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002026
2027 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002028 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002029 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2030 if (Str[i] != '\\') {
2031 Data += Str[i];
2032 continue;
2033 }
2034
2035 // Recognize escaped characters. Note that this escape semantics currently
2036 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2037 ++i;
2038 if (i == e)
2039 return TokError("unexpected backslash at end of string");
2040
2041 // Recognize octal sequences.
2042 if ((unsigned) (Str[i] - '0') <= 7) {
2043 // Consume up to three octal characters.
2044 unsigned Value = Str[i] - '0';
2045
2046 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2047 ++i;
2048 Value = Value * 8 + (Str[i] - '0');
2049
2050 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2051 ++i;
2052 Value = Value * 8 + (Str[i] - '0');
2053 }
2054 }
2055
2056 if (Value > 255)
2057 return TokError("invalid octal escape sequence (out of range)");
2058
2059 Data += (unsigned char) Value;
2060 continue;
2061 }
2062
2063 // Otherwise recognize individual escapes.
2064 switch (Str[i]) {
2065 default:
2066 // Just reject invalid escape sequences for now.
2067 return TokError("invalid escape sequence (unrecognized character)");
2068
2069 case 'b': Data += '\b'; break;
2070 case 'f': Data += '\f'; break;
2071 case 'n': Data += '\n'; break;
2072 case 'r': Data += '\r'; break;
2073 case 't': Data += '\t'; break;
2074 case '"': Data += '"'; break;
2075 case '\\': Data += '\\'; break;
2076 }
2077 }
2078
2079 return false;
2080}
2081
Daniel Dunbara0d14262009-06-24 23:30:00 +00002082/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002083/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2084bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002085 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002086 CheckForValidSection();
2087
Daniel Dunbara0d14262009-06-24 23:30:00 +00002088 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002089 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002090 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002091
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002092 std::string Data;
2093 if (ParseEscapedString(Data))
2094 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002095
2096 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002097 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002098 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2099
Sean Callanan79ed1a82010-01-19 20:22:31 +00002100 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002101
2102 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002103 break;
2104
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002105 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002106 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002107 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002108 }
2109 }
2110
Sean Callanan79ed1a82010-01-19 20:22:31 +00002111 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002112 return false;
2113}
2114
2115/// ParseDirectiveValue
2116/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2117bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002118 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002119 CheckForValidSection();
2120
Daniel Dunbara0d14262009-06-24 23:30:00 +00002121 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002122 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002123 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002124 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002125 return true;
2126
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002127 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002128 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2129 assert(Size <= 8 && "Invalid size");
2130 uint64_t IntValue = MCE->getValue();
2131 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2132 return Error(ExprLoc, "literal value out of range for directive");
2133 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2134 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002135 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002136
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002137 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002138 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002139
Daniel Dunbara0d14262009-06-24 23:30:00 +00002140 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002141 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002142 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002143 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002144 }
2145 }
2146
Sean Callanan79ed1a82010-01-19 20:22:31 +00002147 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002148 return false;
2149}
2150
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002151/// ParseDirectiveRealValue
2152/// ::= (.single | .double) [ expression (, expression)* ]
2153bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2154 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2155 CheckForValidSection();
2156
2157 for (;;) {
2158 // We don't truly support arithmetic on floating point expressions, so we
2159 // have to manually parse unary prefixes.
2160 bool IsNeg = false;
2161 if (getLexer().is(AsmToken::Minus)) {
2162 Lex();
2163 IsNeg = true;
2164 } else if (getLexer().is(AsmToken::Plus))
2165 Lex();
2166
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002167 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002168 getLexer().isNot(AsmToken::Real) &&
2169 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002170 return TokError("unexpected token in directive");
2171
2172 // Convert to an APFloat.
2173 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002174 StringRef IDVal = getTok().getString();
2175 if (getLexer().is(AsmToken::Identifier)) {
2176 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2177 Value = APFloat::getInf(Semantics);
2178 else if (!IDVal.compare_lower("nan"))
2179 Value = APFloat::getNaN(Semantics, false, ~0);
2180 else
2181 return TokError("invalid floating point literal");
2182 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002183 APFloat::opInvalidOp)
2184 return TokError("invalid floating point literal");
2185 if (IsNeg)
2186 Value.changeSign();
2187
2188 // Consume the numeric token.
2189 Lex();
2190
2191 // Emit the value as an integer.
2192 APInt AsInt = Value.bitcastToAPInt();
2193 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2194 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2195
2196 if (getLexer().is(AsmToken::EndOfStatement))
2197 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002198
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002199 if (getLexer().isNot(AsmToken::Comma))
2200 return TokError("unexpected token in directive");
2201 Lex();
2202 }
2203 }
2204
2205 Lex();
2206 return false;
2207}
2208
Daniel Dunbara0d14262009-06-24 23:30:00 +00002209/// ParseDirectiveSpace
2210/// ::= .space expression [ , expression ]
2211bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002212 CheckForValidSection();
2213
Daniel Dunbara0d14262009-06-24 23:30:00 +00002214 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002215 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002216 return true;
2217
2218 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002219 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2220 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002222 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002223
Daniel Dunbar475839e2009-06-29 20:37:27 +00002224 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225 return true;
2226
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002227 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002228 return TokError("unexpected token in '.space' directive");
2229 }
2230
Sean Callanan79ed1a82010-01-19 20:22:31 +00002231 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232
2233 if (NumBytes <= 0)
2234 return TokError("invalid number of bytes in '.space' directive");
2235
2236 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002237 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238
2239 return false;
2240}
2241
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002242/// ParseDirectiveZero
2243/// ::= .zero expression
2244bool AsmParser::ParseDirectiveZero() {
2245 CheckForValidSection();
2246
2247 int64_t NumBytes;
2248 if (ParseAbsoluteExpression(NumBytes))
2249 return true;
2250
Rafael Espindolae452b172010-10-05 19:42:57 +00002251 int64_t Val = 0;
2252 if (getLexer().is(AsmToken::Comma)) {
2253 Lex();
2254 if (ParseAbsoluteExpression(Val))
2255 return true;
2256 }
2257
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002258 if (getLexer().isNot(AsmToken::EndOfStatement))
2259 return TokError("unexpected token in '.zero' directive");
2260
2261 Lex();
2262
Rafael Espindolae452b172010-10-05 19:42:57 +00002263 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002264
2265 return false;
2266}
2267
Daniel Dunbara0d14262009-06-24 23:30:00 +00002268/// ParseDirectiveFill
2269/// ::= .fill expression , expression , expression
2270bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002271 CheckForValidSection();
2272
Daniel Dunbara0d14262009-06-24 23:30:00 +00002273 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002274 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002275 return true;
2276
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002277 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002278 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002279 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002280
Daniel Dunbara0d14262009-06-24 23:30:00 +00002281 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002282 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002283 return true;
2284
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002285 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002286 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002287 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002288
Daniel Dunbara0d14262009-06-24 23:30:00 +00002289 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002290 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002291 return true;
2292
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002293 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002294 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002295
Sean Callanan79ed1a82010-01-19 20:22:31 +00002296 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002297
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002298 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2299 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002300
2301 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002302 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002303
2304 return false;
2305}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002306
2307/// ParseDirectiveOrg
2308/// ::= .org expression [ , expression ]
2309bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002310 CheckForValidSection();
2311
Daniel Dunbar821e3332009-08-31 08:09:28 +00002312 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002313 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002314 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002315 return true;
2316
2317 // Parse optional fill expression.
2318 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002319 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2320 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002321 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002322 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002323
Daniel Dunbar475839e2009-06-29 20:37:27 +00002324 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002325 return true;
2326
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002327 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002328 return TokError("unexpected token in '.org' directive");
2329 }
2330
Sean Callanan79ed1a82010-01-19 20:22:31 +00002331 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002332
Jim Grosbachebd4c052012-01-27 00:37:08 +00002333 // Only limited forms of relocatable expressions are accepted here, it
2334 // has to be relative to the current section. The streamer will return
2335 // 'true' if the expression wasn't evaluatable.
2336 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2337 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002338
2339 return false;
2340}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002341
2342/// ParseDirectiveAlign
2343/// ::= {.align, ...} expression [ , expression [ , expression ]]
2344bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002345 CheckForValidSection();
2346
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002347 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002348 int64_t Alignment;
2349 if (ParseAbsoluteExpression(Alignment))
2350 return true;
2351
2352 SMLoc MaxBytesLoc;
2353 bool HasFillExpr = false;
2354 int64_t FillExpr = 0;
2355 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2357 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002358 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002359 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002360
2361 // The fill expression can be omitted while specifying a maximum number of
2362 // alignment bytes, e.g:
2363 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002364 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002365 HasFillExpr = true;
2366 if (ParseAbsoluteExpression(FillExpr))
2367 return true;
2368 }
2369
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002370 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2371 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002372 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002373 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002374
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002375 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002376 if (ParseAbsoluteExpression(MaxBytesToFill))
2377 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002378
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002379 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002380 return TokError("unexpected token in directive");
2381 }
2382 }
2383
Sean Callanan79ed1a82010-01-19 20:22:31 +00002384 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002385
Daniel Dunbar648ac512010-05-17 21:54:30 +00002386 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002387 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002388
2389 // Compute alignment in bytes.
2390 if (IsPow2) {
2391 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002392 if (Alignment >= 32) {
2393 Error(AlignmentLoc, "invalid alignment value");
2394 Alignment = 31;
2395 }
2396
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002397 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002398 }
2399
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002400 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002401 if (MaxBytesLoc.isValid()) {
2402 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002403 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2404 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002405 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002406 }
2407
2408 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002409 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2410 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002411 MaxBytesToFill = 0;
2412 }
2413 }
2414
Daniel Dunbar648ac512010-05-17 21:54:30 +00002415 // Check whether we should use optimal code alignment for this .align
2416 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002417 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002418 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2419 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002420 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002421 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002422 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002423 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2424 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002425 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426
2427 return false;
2428}
2429
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002430/// ParseDirectiveSymbolAttribute
2431/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002432bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002433 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002434 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002435 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002436 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002437
2438 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002439 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002440
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002441 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002442
Jim Grosbach10ec6502011-09-15 17:56:49 +00002443 // Assembler local symbols don't make any sense here. Complain loudly.
2444 if (Sym->isTemporary())
2445 return Error(Loc, "non-local symbol required in directive");
2446
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002447 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002448
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002449 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002450 break;
2451
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002452 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002453 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002454 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002455 }
2456 }
2457
Sean Callanan79ed1a82010-01-19 20:22:31 +00002458 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002459 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002460}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002461
2462/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002463/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2464bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002465 CheckForValidSection();
2466
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002467 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002468 StringRef Name;
2469 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002470 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002471
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002472 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002473 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002474
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002475 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002476 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002477 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002478
2479 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002480 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002481 if (ParseAbsoluteExpression(Size))
2482 return true;
2483
2484 int64_t Pow2Alignment = 0;
2485 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002486 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002487 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002488 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002489 if (ParseAbsoluteExpression(Pow2Alignment))
2490 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002491
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002492 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2493 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002494 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2495
Chris Lattner258281d2010-01-19 06:22:22 +00002496 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002497 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2498 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002499 if (!isPowerOf2_64(Pow2Alignment))
2500 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2501 Pow2Alignment = Log2_64(Pow2Alignment);
2502 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002503 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002504
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002505 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002506 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002507
Sean Callanan79ed1a82010-01-19 20:22:31 +00002508 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002509
Chris Lattner1fc3d752009-07-09 17:25:12 +00002510 // NOTE: a size of zero for a .comm should create a undefined symbol
2511 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002512 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002513 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2514 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002515
Eric Christopherc260a3e2010-05-14 01:38:54 +00002516 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002517 // may internally end up wanting an alignment in bytes.
2518 // FIXME: Diagnose overflow.
2519 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002520 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2521 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002522
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002523 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002524 return Error(IDLoc, "invalid symbol redefinition");
2525
Chris Lattner1fc3d752009-07-09 17:25:12 +00002526 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002527 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002528 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002529 return false;
2530 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002531
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002532 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002533 return false;
2534}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002535
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002536/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002537/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002538bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002539 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002540 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002541
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002542 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002543 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002544 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002545
Sean Callanan79ed1a82010-01-19 20:22:31 +00002546 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002547
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002548 if (Str.empty())
2549 Error(Loc, ".abort detected. Assembly stopping.");
2550 else
2551 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002552 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002553
2554 return false;
2555}
Kevin Enderby71148242009-07-14 21:35:03 +00002556
Kevin Enderby1f049b22009-07-14 23:21:55 +00002557/// ParseDirectiveInclude
2558/// ::= .include "filename"
2559bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002560 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002561 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002562
Sean Callanan18b83232010-01-19 21:44:56 +00002563 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002564 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002565 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002566
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002567 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002568 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002569
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002570 // Strip the quotes.
2571 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002572
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002573 // Attempt to switch the lexer to the included file before consuming the end
2574 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002575 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002576 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002577 return true;
2578 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002579
2580 return false;
2581}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002582
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002583/// ParseDirectiveIncbin
2584/// ::= .incbin "filename"
2585bool AsmParser::ParseDirectiveIncbin() {
2586 if (getLexer().isNot(AsmToken::String))
2587 return TokError("expected string in '.incbin' directive");
2588
2589 std::string Filename = getTok().getString();
2590 SMLoc IncbinLoc = getLexer().getLoc();
2591 Lex();
2592
2593 if (getLexer().isNot(AsmToken::EndOfStatement))
2594 return TokError("unexpected token in '.incbin' directive");
2595
2596 // Strip the quotes.
2597 Filename = Filename.substr(1, Filename.size()-2);
2598
2599 // Attempt to process the included file.
2600 if (ProcessIncbinFile(Filename)) {
2601 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2602 return true;
2603 }
2604
2605 return false;
2606}
2607
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002608/// ParseDirectiveIf
2609/// ::= .if expression
2610bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002611 TheCondStack.push_back(TheCondState);
2612 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002613 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002614 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002615 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002616 int64_t ExprValue;
2617 if (ParseAbsoluteExpression(ExprValue))
2618 return true;
2619
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002620 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002621 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002622
Sean Callanan79ed1a82010-01-19 20:22:31 +00002623 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002624
2625 TheCondState.CondMet = ExprValue;
2626 TheCondState.Ignore = !TheCondState.CondMet;
2627 }
2628
2629 return false;
2630}
2631
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002632/// ParseDirectiveIfb
2633/// ::= .ifb string
2634bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2635 TheCondStack.push_back(TheCondState);
2636 TheCondState.TheCond = AsmCond::IfCond;
2637
Benjamin Kramer29739e72012-05-12 16:52:21 +00002638 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002639 EatToEndOfStatement();
2640 } else {
2641 StringRef Str = ParseStringToEndOfStatement();
2642
2643 if (getLexer().isNot(AsmToken::EndOfStatement))
2644 return TokError("unexpected token in '.ifb' directive");
2645
2646 Lex();
2647
2648 TheCondState.CondMet = ExpectBlank == Str.empty();
2649 TheCondState.Ignore = !TheCondState.CondMet;
2650 }
2651
2652 return false;
2653}
2654
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002655/// ParseDirectiveIfc
2656/// ::= .ifc string1, string2
2657bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2658 TheCondStack.push_back(TheCondState);
2659 TheCondState.TheCond = AsmCond::IfCond;
2660
Benjamin Kramer29739e72012-05-12 16:52:21 +00002661 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002662 EatToEndOfStatement();
2663 } else {
2664 StringRef Str1 = ParseStringToComma();
2665
2666 if (getLexer().isNot(AsmToken::Comma))
2667 return TokError("unexpected token in '.ifc' directive");
2668
2669 Lex();
2670
2671 StringRef Str2 = ParseStringToEndOfStatement();
2672
2673 if (getLexer().isNot(AsmToken::EndOfStatement))
2674 return TokError("unexpected token in '.ifc' directive");
2675
2676 Lex();
2677
2678 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2679 TheCondState.Ignore = !TheCondState.CondMet;
2680 }
2681
2682 return false;
2683}
2684
2685/// ParseDirectiveIfdef
2686/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002687bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2688 StringRef Name;
2689 TheCondStack.push_back(TheCondState);
2690 TheCondState.TheCond = AsmCond::IfCond;
2691
2692 if (TheCondState.Ignore) {
2693 EatToEndOfStatement();
2694 } else {
2695 if (ParseIdentifier(Name))
2696 return TokError("expected identifier after '.ifdef'");
2697
2698 Lex();
2699
2700 MCSymbol *Sym = getContext().LookupSymbol(Name);
2701
2702 if (expect_defined)
2703 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2704 else
2705 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2706 TheCondState.Ignore = !TheCondState.CondMet;
2707 }
2708
2709 return false;
2710}
2711
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002712/// ParseDirectiveElseIf
2713/// ::= .elseif expression
2714bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2715 if (TheCondState.TheCond != AsmCond::IfCond &&
2716 TheCondState.TheCond != AsmCond::ElseIfCond)
2717 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2718 " an .elseif");
2719 TheCondState.TheCond = AsmCond::ElseIfCond;
2720
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002721 bool LastIgnoreState = false;
2722 if (!TheCondStack.empty())
2723 LastIgnoreState = TheCondStack.back().Ignore;
2724 if (LastIgnoreState || TheCondState.CondMet) {
2725 TheCondState.Ignore = true;
2726 EatToEndOfStatement();
2727 }
2728 else {
2729 int64_t ExprValue;
2730 if (ParseAbsoluteExpression(ExprValue))
2731 return true;
2732
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002733 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002734 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002735
Sean Callanan79ed1a82010-01-19 20:22:31 +00002736 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002737 TheCondState.CondMet = ExprValue;
2738 TheCondState.Ignore = !TheCondState.CondMet;
2739 }
2740
2741 return false;
2742}
2743
2744/// ParseDirectiveElse
2745/// ::= .else
2746bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002747 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002748 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002749
Sean Callanan79ed1a82010-01-19 20:22:31 +00002750 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002751
2752 if (TheCondState.TheCond != AsmCond::IfCond &&
2753 TheCondState.TheCond != AsmCond::ElseIfCond)
2754 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2755 ".elseif");
2756 TheCondState.TheCond = AsmCond::ElseCond;
2757 bool LastIgnoreState = false;
2758 if (!TheCondStack.empty())
2759 LastIgnoreState = TheCondStack.back().Ignore;
2760 if (LastIgnoreState || TheCondState.CondMet)
2761 TheCondState.Ignore = true;
2762 else
2763 TheCondState.Ignore = false;
2764
2765 return false;
2766}
2767
2768/// ParseDirectiveEndIf
2769/// ::= .endif
2770bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002771 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002772 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002773
Sean Callanan79ed1a82010-01-19 20:22:31 +00002774 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002775
2776 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2777 TheCondStack.empty())
2778 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2779 ".else");
2780 if (!TheCondStack.empty()) {
2781 TheCondState = TheCondStack.back();
2782 TheCondStack.pop_back();
2783 }
2784
2785 return false;
2786}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002787
2788/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002789/// ::= .file [number] filename
2790/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002791bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002792 // FIXME: I'm not sure what this is.
2793 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002794 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002795 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002796 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002797 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002798
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002799 if (FileNumber < 1)
2800 return TokError("file number less than one");
2801 }
2802
Daniel Dunbareceec052010-07-12 17:45:27 +00002803 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002804 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002805
Nick Lewycky44d798d2011-10-17 23:05:28 +00002806 // Usually the directory and filename together, otherwise just the directory.
2807 StringRef Path = getTok().getString();
2808 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002809 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002810
Nick Lewycky44d798d2011-10-17 23:05:28 +00002811 StringRef Directory;
2812 StringRef Filename;
2813 if (getLexer().is(AsmToken::String)) {
2814 if (FileNumber == -1)
2815 return TokError("explicit path specified, but no file number");
2816 Filename = getTok().getString();
2817 Filename = Filename.substr(1, Filename.size()-2);
2818 Directory = Path;
2819 Lex();
2820 } else {
2821 Filename = Path;
2822 }
2823
Daniel Dunbareceec052010-07-12 17:45:27 +00002824 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002825 return TokError("unexpected token in '.file' directive");
2826
Chris Lattnerd32e8032010-01-25 19:02:58 +00002827 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002828 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002829 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002830 if (getContext().getGenDwarfForAssembly() == true)
2831 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2832 "used to generate dwarf debug info for assembly code");
2833
Nick Lewycky44d798d2011-10-17 23:05:28 +00002834 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002835 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002836 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002837
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002838 return false;
2839}
2840
2841/// ParseDirectiveLine
2842/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002843bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002844 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2845 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002846 return TokError("unexpected token in '.line' directive");
2847
Sean Callanan18b83232010-01-19 21:44:56 +00002848 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002849 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002850 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002851
2852 // FIXME: Do something with the .line.
2853 }
2854
Daniel Dunbareceec052010-07-12 17:45:27 +00002855 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002856 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002857
2858 return false;
2859}
2860
2861
2862/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002863/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002864/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2865/// The first number is a file number, must have been previously assigned with
2866/// a .file directive, the second number is the line number and optionally the
2867/// third number is a column position (zero if not specified). The remaining
2868/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002869bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002870
Daniel Dunbareceec052010-07-12 17:45:27 +00002871 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002872 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002873 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002874 if (FileNumber < 1)
2875 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002876 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002877 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002878 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002879
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002880 int64_t LineNumber = 0;
2881 if (getLexer().is(AsmToken::Integer)) {
2882 LineNumber = getTok().getIntVal();
2883 if (LineNumber < 1)
2884 return TokError("line number less than one in '.loc' directive");
2885 Lex();
2886 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002887
2888 int64_t ColumnPos = 0;
2889 if (getLexer().is(AsmToken::Integer)) {
2890 ColumnPos = getTok().getIntVal();
2891 if (ColumnPos < 0)
2892 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002893 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002894 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002895
Kevin Enderbyc0957932010-09-30 16:52:03 +00002896 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002897 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002898 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002899 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2900 for (;;) {
2901 if (getLexer().is(AsmToken::EndOfStatement))
2902 break;
2903
2904 StringRef Name;
2905 SMLoc Loc = getTok().getLoc();
2906 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002907 return TokError("unexpected token in '.loc' directive");
2908
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002909 if (Name == "basic_block")
2910 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2911 else if (Name == "prologue_end")
2912 Flags |= DWARF2_FLAG_PROLOGUE_END;
2913 else if (Name == "epilogue_begin")
2914 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2915 else if (Name == "is_stmt") {
2916 SMLoc Loc = getTok().getLoc();
2917 const MCExpr *Value;
2918 if (getParser().ParseExpression(Value))
2919 return true;
2920 // The expression must be the constant 0 or 1.
2921 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2922 int Value = MCE->getValue();
2923 if (Value == 0)
2924 Flags &= ~DWARF2_FLAG_IS_STMT;
2925 else if (Value == 1)
2926 Flags |= DWARF2_FLAG_IS_STMT;
2927 else
2928 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002929 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002930 else {
2931 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2932 }
2933 }
2934 else if (Name == "isa") {
2935 SMLoc Loc = getTok().getLoc();
2936 const MCExpr *Value;
2937 if (getParser().ParseExpression(Value))
2938 return true;
2939 // The expression must be a constant greater or equal to 0.
2940 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2941 int Value = MCE->getValue();
2942 if (Value < 0)
2943 return Error(Loc, "isa number less than zero");
2944 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002945 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002946 else {
2947 return Error(Loc, "isa number not a constant value");
2948 }
2949 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002950 else if (Name == "discriminator") {
2951 if (getParser().ParseAbsoluteExpression(Discriminator))
2952 return true;
2953 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002954 else {
2955 return Error(Loc, "unknown sub-directive in '.loc' directive");
2956 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002957
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002958 if (getLexer().is(AsmToken::EndOfStatement))
2959 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002960 }
2961 }
2962
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002963 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002964 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002965
2966 return false;
2967}
2968
Daniel Dunbar138abae2010-10-16 04:56:42 +00002969/// ParseDirectiveStabs
2970/// ::= .stabs string, number, number, number
2971bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2972 SMLoc DirectiveLoc) {
2973 return TokError("unsupported directive '" + Directive + "'");
2974}
2975
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002976/// ParseDirectiveCFISections
2977/// ::= .cfi_sections section [, section]
2978bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2979 SMLoc DirectiveLoc) {
2980 StringRef Name;
2981 bool EH = false;
2982 bool Debug = false;
2983
2984 if (getParser().ParseIdentifier(Name))
2985 return TokError("Expected an identifier");
2986
2987 if (Name == ".eh_frame")
2988 EH = true;
2989 else if (Name == ".debug_frame")
2990 Debug = true;
2991
2992 if (getLexer().is(AsmToken::Comma)) {
2993 Lex();
2994
2995 if (getParser().ParseIdentifier(Name))
2996 return TokError("Expected an identifier");
2997
2998 if (Name == ".eh_frame")
2999 EH = true;
3000 else if (Name == ".debug_frame")
3001 Debug = true;
3002 }
3003
3004 getStreamer().EmitCFISections(EH, Debug);
3005
3006 return false;
3007}
3008
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003009/// ParseDirectiveCFIStartProc
3010/// ::= .cfi_startproc
3011bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3012 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003013 getStreamer().EmitCFIStartProc();
3014 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003015}
3016
3017/// ParseDirectiveCFIEndProc
3018/// ::= .cfi_endproc
3019bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003020 getStreamer().EmitCFIEndProc();
3021 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003022}
3023
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003024/// ParseRegisterOrRegisterNumber - parse register name or number.
3025bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3026 SMLoc DirectiveLoc) {
3027 unsigned RegNo;
3028
Jim Grosbach6f888a82011-06-02 17:14:04 +00003029 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003030 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3031 DirectiveLoc))
3032 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003033 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003034 } else
3035 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003036
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003037 return false;
3038}
3039
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003040/// ParseDirectiveCFIDefCfa
3041/// ::= .cfi_def_cfa register, offset
3042bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3043 SMLoc DirectiveLoc) {
3044 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003045 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003046 return true;
3047
3048 if (getLexer().isNot(AsmToken::Comma))
3049 return TokError("unexpected token in directive");
3050 Lex();
3051
3052 int64_t Offset = 0;
3053 if (getParser().ParseAbsoluteExpression(Offset))
3054 return true;
3055
Rafael Espindola066c2f42011-04-12 23:59:07 +00003056 getStreamer().EmitCFIDefCfa(Register, Offset);
3057 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003058}
3059
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003060/// ParseDirectiveCFIDefCfaOffset
3061/// ::= .cfi_def_cfa_offset offset
3062bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3063 SMLoc DirectiveLoc) {
3064 int64_t Offset = 0;
3065 if (getParser().ParseAbsoluteExpression(Offset))
3066 return true;
3067
Rafael Espindola066c2f42011-04-12 23:59:07 +00003068 getStreamer().EmitCFIDefCfaOffset(Offset);
3069 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003070}
3071
3072/// ParseDirectiveCFIAdjustCfaOffset
3073/// ::= .cfi_adjust_cfa_offset adjustment
3074bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3075 SMLoc DirectiveLoc) {
3076 int64_t Adjustment = 0;
3077 if (getParser().ParseAbsoluteExpression(Adjustment))
3078 return true;
3079
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003080 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3081 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003082}
3083
3084/// ParseDirectiveCFIDefCfaRegister
3085/// ::= .cfi_def_cfa_register register
3086bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3087 SMLoc DirectiveLoc) {
3088 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003089 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003090 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003091
Rafael Espindola066c2f42011-04-12 23:59:07 +00003092 getStreamer().EmitCFIDefCfaRegister(Register);
3093 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003094}
3095
3096/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003097/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003098bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3099 int64_t Register = 0;
3100 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003101
3102 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003103 return true;
3104
3105 if (getLexer().isNot(AsmToken::Comma))
3106 return TokError("unexpected token in directive");
3107 Lex();
3108
3109 if (getParser().ParseAbsoluteExpression(Offset))
3110 return true;
3111
Rafael Espindola066c2f42011-04-12 23:59:07 +00003112 getStreamer().EmitCFIOffset(Register, Offset);
3113 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003114}
3115
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003116/// ParseDirectiveCFIRelOffset
3117/// ::= .cfi_rel_offset register, offset
3118bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3119 SMLoc DirectiveLoc) {
3120 int64_t Register = 0;
3121
3122 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3123 return true;
3124
3125 if (getLexer().isNot(AsmToken::Comma))
3126 return TokError("unexpected token in directive");
3127 Lex();
3128
3129 int64_t Offset = 0;
3130 if (getParser().ParseAbsoluteExpression(Offset))
3131 return true;
3132
Rafael Espindola25f492e2011-04-12 16:12:03 +00003133 getStreamer().EmitCFIRelOffset(Register, Offset);
3134 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003135}
3136
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003137static bool isValidEncoding(int64_t Encoding) {
3138 if (Encoding & ~0xff)
3139 return false;
3140
3141 if (Encoding == dwarf::DW_EH_PE_omit)
3142 return true;
3143
3144 const unsigned Format = Encoding & 0xf;
3145 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3146 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3147 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3148 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3149 return false;
3150
Rafael Espindolacaf11582010-12-29 04:31:26 +00003151 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003152 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003153 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003154 return false;
3155
3156 return true;
3157}
3158
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003159/// ParseDirectiveCFIPersonalityOrLsda
3160/// ::= .cfi_personality encoding, [symbol_name]
3161/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003162bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003163 SMLoc DirectiveLoc) {
3164 int64_t Encoding = 0;
3165 if (getParser().ParseAbsoluteExpression(Encoding))
3166 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003167 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003168 return false;
3169
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003170 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003171 return TokError("unsupported encoding.");
3172
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003173 if (getLexer().isNot(AsmToken::Comma))
3174 return TokError("unexpected token in directive");
3175 Lex();
3176
3177 StringRef Name;
3178 if (getParser().ParseIdentifier(Name))
3179 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003180
3181 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3182
3183 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003184 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003185 else {
3186 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003187 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003188 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003189 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003190}
3191
Rafael Espindolafe024d02010-12-28 18:36:23 +00003192/// ParseDirectiveCFIRememberState
3193/// ::= .cfi_remember_state
3194bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3195 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003196 getStreamer().EmitCFIRememberState();
3197 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003198}
3199
3200/// ParseDirectiveCFIRestoreState
3201/// ::= .cfi_remember_state
3202bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3203 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003204 getStreamer().EmitCFIRestoreState();
3205 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003206}
3207
Rafael Espindolac5754392011-04-12 15:31:05 +00003208/// ParseDirectiveCFISameValue
3209/// ::= .cfi_same_value register
3210bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3211 SMLoc DirectiveLoc) {
3212 int64_t Register = 0;
3213
3214 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3215 return true;
3216
3217 getStreamer().EmitCFISameValue(Register);
3218
3219 return false;
3220}
3221
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003222/// ParseDirectiveCFIRestore
3223/// ::= .cfi_restore register
3224bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003225 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003226 int64_t Register = 0;
3227 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3228 return true;
3229
3230 getStreamer().EmitCFIRestore(Register);
3231
3232 return false;
3233}
3234
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003235/// ParseDirectiveCFIEscape
3236/// ::= .cfi_escape expression[,...]
3237bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003238 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003239 std::string Values;
3240 int64_t CurrValue;
3241 if (getParser().ParseAbsoluteExpression(CurrValue))
3242 return true;
3243
3244 Values.push_back((uint8_t)CurrValue);
3245
3246 while (getLexer().is(AsmToken::Comma)) {
3247 Lex();
3248
3249 if (getParser().ParseAbsoluteExpression(CurrValue))
3250 return true;
3251
3252 Values.push_back((uint8_t)CurrValue);
3253 }
3254
3255 getStreamer().EmitCFIEscape(Values);
3256 return false;
3257}
3258
Rafael Espindola16d7d432012-01-23 21:51:52 +00003259/// ParseDirectiveCFISignalFrame
3260/// ::= .cfi_signal_frame
3261bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3262 SMLoc DirectiveLoc) {
3263 if (getLexer().isNot(AsmToken::EndOfStatement))
3264 return Error(getLexer().getLoc(),
3265 "unexpected token in '" + Directive + "' directive");
3266
3267 getStreamer().EmitCFISignalFrame();
3268
3269 return false;
3270}
3271
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003272/// ParseDirectiveCFIUndefined
3273/// ::= .cfi_undefined register
3274bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3275 SMLoc DirectiveLoc) {
3276 int64_t Register = 0;
3277
3278 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3279 return true;
3280
3281 getStreamer().EmitCFIUndefined(Register);
3282
3283 return false;
3284}
3285
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003286/// ParseDirectiveCFIRegister
3287/// ::= .cfi_register register, register
3288bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3289 SMLoc DirectiveLoc) {
3290 int64_t Register1 = 0;
3291
3292 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3293 return true;
3294
3295 if (getLexer().isNot(AsmToken::Comma))
3296 return TokError("unexpected token in directive");
3297 Lex();
3298
3299 int64_t Register2 = 0;
3300
3301 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3302 return true;
3303
3304 getStreamer().EmitCFIRegister(Register1, Register2);
3305
3306 return false;
3307}
3308
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003309/// ParseDirectiveMacrosOnOff
3310/// ::= .macros_on
3311/// ::= .macros_off
3312bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3313 SMLoc DirectiveLoc) {
3314 if (getLexer().isNot(AsmToken::EndOfStatement))
3315 return Error(getLexer().getLoc(),
3316 "unexpected token in '" + Directive + "' directive");
3317
3318 getParser().MacrosEnabled = Directive == ".macros_on";
3319
3320 return false;
3321}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003322
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003323/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003324/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003325bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3326 SMLoc DirectiveLoc) {
3327 StringRef Name;
3328 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003329 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003330
Rafael Espindola8a403d32012-08-08 14:51:03 +00003331 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003332 // Argument delimiter is initially unknown. It will be set by
3333 // ParseMacroArgument()
3334 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003335 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003336 for (;;) {
3337 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003338 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003339 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003340
3341 if (getLexer().is(AsmToken::Equal)) {
3342 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003343 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003344 return true;
3345 }
3346
Rafael Espindola65366442011-06-05 02:43:45 +00003347 Parameters.push_back(Parameter);
3348
Preston Gurd7b6f2032012-09-19 20:36:12 +00003349 if (getLexer().is(AsmToken::Comma))
3350 Lex();
3351 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003352 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003353 }
3354 }
3355
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003356 // Eat the end of statement.
3357 Lex();
3358
3359 AsmToken EndToken, StartToken = getTok();
3360
3361 // Lex the macro definition.
3362 for (;;) {
3363 // Check whether we have reached the end of the file.
3364 if (getLexer().is(AsmToken::Eof))
3365 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3366
3367 // Otherwise, check whether we have reach the .endmacro.
3368 if (getLexer().is(AsmToken::Identifier) &&
3369 (getTok().getIdentifier() == ".endm" ||
3370 getTok().getIdentifier() == ".endmacro")) {
3371 EndToken = getTok();
3372 Lex();
3373 if (getLexer().isNot(AsmToken::EndOfStatement))
3374 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3375 "' directive");
3376 break;
3377 }
3378
3379 // Otherwise, scan til the end of the statement.
3380 getParser().EatToEndOfStatement();
3381 }
3382
3383 if (getParser().MacroMap.lookup(Name)) {
3384 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3385 }
3386
3387 const char *BodyStart = StartToken.getLoc().getPointer();
3388 const char *BodyEnd = EndToken.getLoc().getPointer();
3389 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003390 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003391 return false;
3392}
3393
3394/// ParseDirectiveEndMacro
3395/// ::= .endm
3396/// ::= .endmacro
3397bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003398 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003399 if (getLexer().isNot(AsmToken::EndOfStatement))
3400 return TokError("unexpected token in '" + Directive + "' directive");
3401
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003402 // If we are inside a macro instantiation, terminate the current
3403 // instantiation.
3404 if (!getParser().ActiveMacros.empty()) {
3405 getParser().HandleMacroExit();
3406 return false;
3407 }
3408
3409 // Otherwise, this .endmacro is a stray entry in the file; well formed
3410 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003411 return TokError("unexpected '" + Directive + "' in file, "
3412 "no current macro definition");
3413}
3414
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003415/// ParseDirectivePurgeMacro
3416/// ::= .purgem
3417bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3418 SMLoc DirectiveLoc) {
3419 StringRef Name;
3420 if (getParser().ParseIdentifier(Name))
3421 return TokError("expected identifier in '.purgem' directive");
3422
3423 if (getLexer().isNot(AsmToken::EndOfStatement))
3424 return TokError("unexpected token in '.purgem' directive");
3425
3426 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3427 if (I == getParser().MacroMap.end())
3428 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3429
3430 // Undefine the macro.
3431 delete I->getValue();
3432 getParser().MacroMap.erase(I);
3433 return false;
3434}
3435
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003436bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003437 getParser().CheckForValidSection();
3438
3439 const MCExpr *Value;
3440
3441 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003442 return true;
3443
3444 if (getLexer().isNot(AsmToken::EndOfStatement))
3445 return TokError("unexpected token in directive");
3446
3447 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003448 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003449 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003450 getStreamer().EmitULEB128Value(Value);
3451
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003452 return false;
3453}
3454
Rafael Espindola761cb062012-06-03 23:57:14 +00003455Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003456 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003457
Rafael Espindola761cb062012-06-03 23:57:14 +00003458 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003459 for (;;) {
3460 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003461 if (getLexer().is(AsmToken::Eof)) {
3462 Error(DirectiveLoc, "no matching '.endr' in definition");
3463 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003464 }
3465
Rafael Espindola761cb062012-06-03 23:57:14 +00003466 if (Lexer.is(AsmToken::Identifier) &&
3467 (getTok().getIdentifier() == ".rept")) {
3468 ++NestLevel;
3469 }
3470
3471 // Otherwise, check whether we have reached the .endr.
3472 if (Lexer.is(AsmToken::Identifier) &&
3473 getTok().getIdentifier() == ".endr") {
3474 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003475 EndToken = getTok();
3476 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003477 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3478 TokError("unexpected token in '.endr' directive");
3479 return 0;
3480 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003481 break;
3482 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003483 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003484 }
3485
Rafael Espindola761cb062012-06-03 23:57:14 +00003486 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003487 EatToEndOfStatement();
3488 }
3489
3490 const char *BodyStart = StartToken.getLoc().getPointer();
3491 const char *BodyEnd = EndToken.getLoc().getPointer();
3492 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3493
Rafael Espindola761cb062012-06-03 23:57:14 +00003494 // We Are Anonymous.
3495 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003496 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003497 return new Macro(Name, Body, Parameters);
3498}
3499
3500void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3501 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003502 OS << ".endr\n";
3503
3504 MemoryBuffer *Instantiation =
3505 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3506
Rafael Espindola761cb062012-06-03 23:57:14 +00003507 // Create the macro instantiation object and add to the current macro
3508 // instantiation stack.
3509 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003510 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003511 getTok().getLoc(),
3512 Instantiation);
3513 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003514
Rafael Espindola761cb062012-06-03 23:57:14 +00003515 // Jump to the macro instantiation and prime the lexer.
3516 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3517 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3518 Lex();
3519}
3520
3521bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3522 int64_t Count;
3523 if (ParseAbsoluteExpression(Count))
3524 return TokError("unexpected token in '.rept' directive");
3525
3526 if (Count < 0)
3527 return TokError("Count is negative");
3528
3529 if (Lexer.isNot(AsmToken::EndOfStatement))
3530 return TokError("unexpected token in '.rept' directive");
3531
3532 // Eat the end of statement.
3533 Lex();
3534
3535 // Lex the rept definition.
3536 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3537 if (!M)
3538 return true;
3539
3540 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3541 // to hold the macro body with substitutions.
3542 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003543 MacroParameters Parameters;
3544 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003545 raw_svector_ostream OS(Buf);
3546 while (Count--) {
3547 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3548 return true;
3549 }
3550 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003551
3552 return false;
3553}
3554
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003555/// ParseDirectiveIrp
3556/// ::= .irp symbol,values
3557bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003558 MacroParameters Parameters;
3559 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003560
Preston Gurd6c9176a2012-09-19 20:29:04 +00003561 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003562 return TokError("expected identifier in '.irp' directive");
3563
3564 Parameters.push_back(Parameter);
3565
3566 if (Lexer.isNot(AsmToken::Comma))
3567 return TokError("expected comma in '.irp' directive");
3568
3569 Lex();
3570
Rafael Espindola8a403d32012-08-08 14:51:03 +00003571 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003572 if (ParseMacroArguments(0, A))
3573 return true;
3574
3575 // Eat the end of statement.
3576 Lex();
3577
3578 // Lex the irp definition.
3579 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3580 if (!M)
3581 return true;
3582
3583 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3584 // to hold the macro body with substitutions.
3585 SmallString<256> Buf;
3586 raw_svector_ostream OS(Buf);
3587
Rafael Espindola7996d042012-08-21 16:06:48 +00003588 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3589 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003590 Args.push_back(*i);
3591
3592 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3593 return true;
3594 }
3595
3596 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3597
3598 return false;
3599}
3600
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003601/// ParseDirectiveIrpc
3602/// ::= .irpc symbol,values
3603bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003604 MacroParameters Parameters;
3605 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003606
Preston Gurd6c9176a2012-09-19 20:29:04 +00003607 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003608 return TokError("expected identifier in '.irpc' directive");
3609
3610 Parameters.push_back(Parameter);
3611
3612 if (Lexer.isNot(AsmToken::Comma))
3613 return TokError("expected comma in '.irpc' directive");
3614
3615 Lex();
3616
Rafael Espindola8a403d32012-08-08 14:51:03 +00003617 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003618 if (ParseMacroArguments(0, A))
3619 return true;
3620
3621 if (A.size() != 1 || A.front().size() != 1)
3622 return TokError("unexpected token in '.irpc' directive");
3623
3624 // Eat the end of statement.
3625 Lex();
3626
3627 // Lex the irpc definition.
3628 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3629 if (!M)
3630 return true;
3631
3632 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3633 // to hold the macro body with substitutions.
3634 SmallString<256> Buf;
3635 raw_svector_ostream OS(Buf);
3636
3637 StringRef Values = A.front().front().getString();
3638 std::size_t I, End = Values.size();
3639 for (I = 0; I < End; ++I) {
3640 MacroArgument Arg;
3641 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3642
Rafael Espindola8a403d32012-08-08 14:51:03 +00003643 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003644 Args.push_back(Arg);
3645
3646 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3647 return true;
3648 }
3649
3650 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3651
3652 return false;
3653}
3654
Rafael Espindola761cb062012-06-03 23:57:14 +00003655bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3656 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003657 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003658
3659 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003660 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003661 assert(getLexer().is(AsmToken::EndOfStatement));
3662
Rafael Espindola761cb062012-06-03 23:57:14 +00003663 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003664 return false;
3665}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003666
Eli Friedman2128aae2012-10-22 23:58:19 +00003667bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3668 const MCExpr *Value;
3669 SMLoc ExprLoc = getLexer().getLoc();
3670 if (ParseExpression(Value))
3671 return true;
3672 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3673 if (!MCE)
3674 return Error(ExprLoc, "unexpected expression in _emit");
3675 uint64_t IntValue = MCE->getValue();
3676 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3677 return Error(ExprLoc, "literal value out of range for directive");
3678
3679 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3680 return false;
3681}
3682
Chad Rosierb1f8c132012-10-18 15:49:34 +00003683bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3684 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003685 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003686 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003687 SmallVectorImpl<std::string> &Clobbers,
3688 const MCInstrInfo *MII,
3689 const MCInstPrinter *IP,
3690 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003691 SmallVector<void *, 4> InputDecls;
3692 SmallVector<void *, 4> OutputDecls;
3693 SmallVector<bool, 4> InputDeclsOffsetOf;
3694 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003695 SmallVector<std::string, 4> InputConstraints;
3696 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003697 std::set<std::string> ClobberRegs;
3698
Chad Rosier4e472d22012-10-20 01:02:45 +00003699 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003700
3701 // Prime the lexer.
3702 Lex();
3703
3704 // While we have input, parse each statement.
3705 unsigned InputIdx = 0;
3706 unsigned OutputIdx = 0;
3707 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003708 ParseStatementInfo Info(&AsmStrRewrites);
3709 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003710 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003711
Chad Rosier57498012012-12-12 22:45:52 +00003712 if (Info.ParseError)
3713 return true;
3714
Eli Friedman2128aae2012-10-22 23:58:19 +00003715 if (Info.Opcode != ~0U) {
3716 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003717
3718 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003719 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3720 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003721
3722 // Immediate.
3723 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003724 if (Operand->needAsmRewrite())
3725 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3726 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003727 continue;
3728 }
3729
3730 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003731 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003732 unsigned NumDefs = Desc.getNumDefs();
3733 // Clobber.
3734 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3735 std::string Reg;
3736 raw_string_ostream OS(Reg);
3737 IP->printRegName(OS, Operand->getReg());
3738 ClobberRegs.insert(StringRef(OS.str()));
3739 }
3740 continue;
3741 }
3742
3743 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003744 unsigned Size;
3745 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3746 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003747 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003748 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003749 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003750 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003751 Operand->getStartLoc(),
3752 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003753 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003754 if (isOutput) {
3755 std::string Constraint = "=";
3756 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003757 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003758 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003759 Constraint += Operand->getConstraint().str();
3760 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003761 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003762 Operand->getStartLoc(),
3763 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003764 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003765 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003766 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003767 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003768 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003769 Operand->getStartLoc(),
3770 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003771 }
3772 }
3773 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003774 }
3775 }
3776
3777 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003778 NumOutputs = OutputDecls.size();
3779 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003780
3781 // Set the unique clobbers.
3782 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3783 E = ClobberRegs.end(); I != E; ++I)
3784 Clobbers.push_back(*I);
3785
3786 // Merge the various outputs and inputs. Output are expected first.
3787 if (NumOutputs || NumInputs) {
3788 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003789 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003790 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003791 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3792 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003793 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003794 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3795 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003796 }
3797 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003798 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3799 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003800 }
3801 }
3802
3803 // Build the IR assembly string.
3804 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003805 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003806 raw_string_ostream OS(AsmStringIR);
3807 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003808 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003809 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3810 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003811
Chad Rosier4e472d22012-10-20 01:02:45 +00003812 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003813
3814 // Emit everything up to the immediate/expression. If the previous rewrite
3815 // was a size directive, then this has already been done.
3816 if (PrevKind != AOK_SizeDirective)
3817 OS << StringRef(Start, Loc - Start);
3818 PrevKind = Kind;
3819
Chad Rosier5a719fc2012-10-23 17:43:43 +00003820 // Skip the original expression.
3821 if (Kind == AOK_Skip) {
3822 Start = Loc + (*I).Len;
3823 continue;
3824 }
3825
Chad Rosierb1f8c132012-10-18 15:49:34 +00003826 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003827 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003828 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003829 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003830 OS << Twine("$$");
3831 OS << (*I).Val;
3832 break;
3833 case AOK_ImmPrefix:
3834 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003835 break;
3836 case AOK_Input:
3837 OS << '$';
3838 OS << InputIdx++;
3839 break;
3840 case AOK_Output:
3841 OS << '$';
3842 OS << OutputIdx++;
3843 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003844 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003845 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003846 default: break;
3847 case 8: OS << "byte ptr "; break;
3848 case 16: OS << "word ptr "; break;
3849 case 32: OS << "dword ptr "; break;
3850 case 64: OS << "qword ptr "; break;
3851 case 80: OS << "xword ptr "; break;
3852 case 128: OS << "xmmword ptr "; break;
3853 case 256: OS << "ymmword ptr "; break;
3854 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003855 break;
3856 case AOK_Emit:
3857 OS << ".byte";
3858 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003859 case AOK_DotOperator:
3860 OS << (*I).Val;
3861 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003862 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003863
Chad Rosierb1f8c132012-10-18 15:49:34 +00003864 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003865 if (Kind != AOK_SizeDirective)
3866 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003867 }
3868
3869 // Emit the remainder of the asm string.
3870 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3871 if (Start != AsmEnd)
3872 OS << StringRef(Start, AsmEnd - Start);
3873
3874 AsmString = OS.str();
3875 return false;
3876}
3877
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003878/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003879MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003880 MCContext &C, MCStreamer &Out,
3881 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003882 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003883}