blob: ae3d660ff91b86f9d568fada39fa79a9963a1131 [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
81 /// The location where parsing should resume upon instantiation completion.
82 SMLoc ExitLoc;
83
84public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000085 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000086 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000087};
88
Chad Rosier6a020a72012-10-25 20:41:34 +000089//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000090struct ParseStatementInfo {
91 /// ParsedOperands - The parsed operands from the last parsed statement.
92 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
93
94 /// Opcode - The opcode from the last parsed instruction.
95 unsigned Opcode;
96
97 SmallVectorImpl<AsmRewrite> *AsmRewrites;
98
99 ParseStatementInfo() : Opcode(~0U), AsmRewrites(0) {}
100 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
101 : Opcode(~0), AsmRewrites(rewrites) {}
102
103 ~ParseStatementInfo() {
104 // Free any parsed operands.
105 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
106 delete ParsedOperands[i];
107 ParsedOperands.clear();
108 }
109};
110
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000111/// \brief The concrete assembly parser instance.
112class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000113 friend class GenericAsmParser;
114
Craig Topper85aadc02012-09-15 16:23:52 +0000115 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
116 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000117private:
118 AsmLexer Lexer;
119 MCContext &Ctx;
120 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000121 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000122 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000125 MCAsmParserExtension *GenericParser;
126 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000127
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
130 int CurBuffer;
131
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
134
135 /// DirectiveMap - This is a table handlers for directives. Each handler is
136 /// invoked after the directive identifier is read and is responsible for
137 /// parsing and validating the rest of the directive. The handler is passed
138 /// in the directive name and the location of the directive keyword.
139 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000140
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000141 /// MacroMap - Map of currently defined macros.
142 StringMap<Macro*> MacroMap;
143
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000144 /// ActiveMacros - Stack of active macro instantiations.
145 std::vector<MacroInstantiation*> ActiveMacros;
146
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabled : 1;
149
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000150 /// Flag tracking whether any errors have been encountered.
151 unsigned HadError : 1;
152
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000153 /// The values from the last parsed cpp hash file line comment if any.
154 StringRef CppHashFilename;
155 int64_t CppHashLineNumber;
156 SMLoc CppHashLoc;
157
Devang Patel0db58bf2012-01-31 18:14:05 +0000158 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
159 unsigned AssemblerDialect;
160
Preston Gurd7b6f2032012-09-19 20:36:12 +0000161 /// IsDarwin - is Darwin compatibility enabled?
162 bool IsDarwin;
163
Chad Rosier8f138d12012-10-15 17:19:13 +0000164 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000165 bool ParsingInlineAsm;
166
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000167public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000168 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000169 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000170 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000171
172 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
173
Craig Topper345d16d2012-08-29 05:48:09 +0000174 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
175 StringRef Directive,
176 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177 DirectiveMap[Directive] = std::make_pair(Object, Handler);
178 }
179
180public:
181 /// @name MCAsmParser Interface
182 /// {
183
184 virtual SourceMgr &getSourceManager() { return SrcMgr; }
185 virtual MCAsmLexer &getLexer() { return Lexer; }
186 virtual MCContext &getContext() { return Ctx; }
187 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000188 virtual unsigned getAssemblerDialect() {
189 if (AssemblerDialect == ~0U)
190 return MAI.getAssemblerDialect();
191 else
192 return AssemblerDialect;
193 }
194 virtual void setAssemblerDialect(unsigned i) {
195 AssemblerDialect = i;
196 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000197
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000198 virtual bool Warning(SMLoc L, const Twine &Msg,
199 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
200 virtual bool Error(SMLoc L, const Twine &Msg,
201 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202
Craig Topper345d16d2012-08-29 05:48:09 +0000203 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000204
Chad Rosier84125ca2012-10-13 00:26:04 +0000205 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000206 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000207
208 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
209 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000210 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000211 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212 SmallVectorImpl<std::string> &Clobbers,
213 const MCInstrInfo *MII,
214 const MCInstPrinter *IP,
215 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000216
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000217 bool ParseExpression(const MCExpr *&Res);
218 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
219 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
220 virtual bool ParseAbsoluteExpression(int64_t &Res);
221
222 /// }
223
224private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000225 void CheckForValidSection();
226
Eli Friedman2128aae2012-10-22 23:58:19 +0000227 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000228 void EatToEndOfLine();
229 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000230
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000231 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000232 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000233 const MacroParameters &Parameters,
234 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000235 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000236 void HandleMacroExit();
237
238 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000239 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000240 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
241 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000242 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000243 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000244
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000245 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
246 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000247 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
248 /// This returns true on failure.
249 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000250
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000251 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000252 /// current token is not set; clients should ensure Lex() is called
253 /// subsequently.
254 void JumpToLoc(SMLoc Loc);
255
Craig Topper345d16d2012-08-29 05:48:09 +0000256 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000257
Preston Gurd7b6f2032012-09-19 20:36:12 +0000258 bool ParseMacroArgument(MacroArgument &MA,
259 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000260 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000261
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000262 /// \brief Parse up to the end of statement and a return the contents from the
263 /// current token until the end of the statement; the current token on exit
264 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000265 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000266
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000267 /// \brief Parse until the end of a statement or a comma is encountered,
268 /// return the contents from the current token up to the end or comma.
269 StringRef ParseStringToComma();
270
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000271 bool ParseAssignment(StringRef Name, bool allow_redef,
272 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000273
274 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
275 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
276 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000277 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000278
279 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000280 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000281 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000282
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000284
285 // ".ascii", ".asciiz", ".string"
286 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000287 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000288 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000289 bool ParseDirectiveFill(); // ".fill"
290 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000291 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000292 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000293 bool ParseDirectiveOrg(); // ".org"
294 // ".align{,32}", ".p2align{,w,l}"
295 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
296
297 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
298 /// accepts a single symbol (which should be a label or an external).
299 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000300
301 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
302
303 bool ParseDirectiveAbort(); // ".abort"
304 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000305 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000306
307 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000308 // ".ifb" or ".ifnb", depending on ExpectBlank.
309 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000310 // ".ifc" or ".ifnc", depending on ExpectEqual.
311 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000312 // ".ifdef" or ".ifndef", depending on expect_defined
313 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000314 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
315 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
316 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
317
318 /// ParseEscapedString - Parse the current token as a string which may include
319 /// escaped characters and return the string contents.
320 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000321
322 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
323 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000324
Rafael Espindola761cb062012-06-03 23:57:14 +0000325 // Macro-like directives
326 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
327 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
328 raw_svector_ostream &OS);
329 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000330 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000331 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000332 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000333
Eli Friedman2128aae2012-10-22 23:58:19 +0000334 // "_emit"
335 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000336};
337
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000338/// \brief Generic implementations of directive handling, etc. which is shared
339/// (or the default, at least) for all assembler parser.
340class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000341 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
342 void AddDirectiveHandler(StringRef Directive) {
343 getParser().AddDirectiveHandler(this, Directive,
344 HandleDirective<GenericAsmParser, Handler>);
345 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000346public:
347 GenericAsmParser() {}
348
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000349 AsmParser &getParser() {
350 return (AsmParser&) this->MCAsmParserExtension::getParser();
351 }
352
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000353 virtual void Initialize(MCAsmParser &Parser) {
354 // Call the base implementation.
355 this->MCAsmParserExtension::Initialize(Parser);
356
357 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000362
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000363 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000364 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
365 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000366 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
367 ".cfi_startproc");
368 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
369 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000370 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
371 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000372 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
373 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000374 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
375 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000376 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
377 ".cfi_def_cfa_register");
378 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
379 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000380 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
381 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000382 AddDirectiveHandler<
383 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
384 AddDirectiveHandler<
385 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000386 AddDirectiveHandler<
387 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
388 AddDirectiveHandler<
389 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000390 AddDirectiveHandler<
391 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000392 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000393 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
394 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000395 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000396 AddDirectiveHandler<
397 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000398
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000399 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000400 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
401 ".macros_on");
402 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
403 ".macros_off");
404 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000407 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000408
409 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000411 }
412
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000413 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
414
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000415 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000418 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000419 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000420 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
421 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000422 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000423 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000424 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000425 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
426 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000427 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000428 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000429 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
430 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000431 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000432 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000433 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000434 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000435
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000436 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000437 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
438 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000439 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000440
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000441 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000442};
443
444}
445
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000446namespace llvm {
447
448extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000449extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000450extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000451
452}
453
Chris Lattneraaec2052010-01-19 19:46:13 +0000454enum { DEFAULT_ADDRSPACE = 0 };
455
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000456AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000457 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000458 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000459 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000460 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000461 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000462 // Save the old handler.
463 SavedDiagHandler = SrcMgr.getDiagHandler();
464 SavedDiagContext = SrcMgr.getDiagContext();
465 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000466 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000467 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000468
469 // Initialize the generic parser.
470 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000471
472 // Initialize the platform / file format parser.
473 //
474 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
475 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000476 if (_MAI.hasMicrosoftFastStdCallMangling()) {
477 PlatformParser = createCOFFAsmParser();
478 PlatformParser->Initialize(*this);
479 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000480 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000481 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000482 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000483 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000484 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000485 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000486 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000487}
488
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000489AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000490 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
491
492 // Destroy any macros.
493 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
494 ie = MacroMap.end(); it != ie; ++it)
495 delete it->getValue();
496
Daniel Dunbare4749702010-07-12 18:12:02 +0000497 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000498 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000499}
500
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000501void AsmParser::PrintMacroInstantiations() {
502 // Print the active macro instantiation stack.
503 for (std::vector<MacroInstantiation*>::const_reverse_iterator
504 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000505 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
506 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000507}
508
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000509bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000510 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000511 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000512 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000513 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000514 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000515}
516
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000517bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000518 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000519 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000520 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000521 return true;
522}
523
Sean Callananfd0b0282010-01-21 00:19:58 +0000524bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000525 std::string IncludedFile;
526 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000527 if (NewBuf == -1)
528 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000529
Sean Callananfd0b0282010-01-21 00:19:58 +0000530 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000531
Sean Callananfd0b0282010-01-21 00:19:58 +0000532 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000533
Sean Callananfd0b0282010-01-21 00:19:58 +0000534 return false;
535}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000536
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000537/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000538/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000539/// returns true on failure.
540bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
541 std::string IncludedFile;
542 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
543 if (NewBuf == -1)
544 return true;
545
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000546 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000547 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
548 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000549 return false;
550}
551
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000552void AsmParser::JumpToLoc(SMLoc Loc) {
553 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
554 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
555}
556
Sean Callananfd0b0282010-01-21 00:19:58 +0000557const AsmToken &AsmParser::Lex() {
558 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000559
Sean Callananfd0b0282010-01-21 00:19:58 +0000560 if (tok->is(AsmToken::Eof)) {
561 // If this is the end of an included file, pop the parent file off the
562 // include stack.
563 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
564 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000565 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000566 tok = &Lexer.Lex();
567 }
568 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000569
Sean Callananfd0b0282010-01-21 00:19:58 +0000570 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000571 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000572
Sean Callananfd0b0282010-01-21 00:19:58 +0000573 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000574}
575
Chris Lattner79180e22010-04-05 23:15:42 +0000576bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000577 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000578 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000579 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000580
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000581 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000582 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000583
584 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000585 AsmCond StartingCondState = TheCondState;
586
Kevin Enderby613b7572011-11-01 22:27:22 +0000587 // If we are generating dwarf for assembly source files save the initial text
588 // section and generate a .file directive.
589 if (getContext().getGenDwarfForAssembly()) {
590 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000591 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
592 getStreamer().EmitLabel(SectionStartSym);
593 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000594 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
595 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
596 }
597
Chris Lattnerb717fb02009-07-02 21:53:43 +0000598 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000599 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000600 ParseStatementInfo Info;
601 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000602
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000603 // We had an error, validate that one was emitted and recover by skipping to
604 // the next line.
605 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000606 EatToEndOfStatement();
607 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000608
609 if (TheCondState.TheCond != StartingCondState.TheCond ||
610 TheCondState.Ignore != StartingCondState.Ignore)
611 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000612
613 // Check to see there are no empty DwarfFile slots.
614 const std::vector<MCDwarfFile *> &MCDwarfFiles =
615 getContext().getMCDwarfFiles();
616 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000617 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000618 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000619 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000620
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000621 // Check to see that all assembler local symbols were actually defined.
622 // Targets that don't do subsections via symbols may not want this, though,
623 // so conservatively exclude them. Only do this if we're finalizing, though,
624 // as otherwise we won't necessarilly have seen everything yet.
625 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
626 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
627 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
628 e = Symbols.end();
629 i != e; ++i) {
630 MCSymbol *Sym = i->getValue();
631 // Variable symbols may not be marked as defined, so check those
632 // explicitly. If we know it's a variable, we have a definition for
633 // the purposes of this check.
634 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
635 // FIXME: We would really like to refer back to where the symbol was
636 // first referenced for a source location. We need to add something
637 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000638 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
639 "assembler local symbol '" + Sym->getName() +
640 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000641 }
642 }
643
644
Chris Lattner79180e22010-04-05 23:15:42 +0000645 // Finalize the output stream if there are no errors and if the client wants
646 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000647 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000648 Out.Finish();
649
Chris Lattnerb717fb02009-07-02 21:53:43 +0000650 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000651}
652
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000653void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000654 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000655 TokError("expected section directive before assembly directive");
656 Out.SwitchSection(Ctx.getMachOSection(
657 "__TEXT", "__text",
658 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
659 0, SectionKind::getText()));
660 }
661}
662
Chris Lattner2cf5f142009-06-22 01:29:09 +0000663/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
664void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000665 while (Lexer.isNot(AsmToken::EndOfStatement) &&
666 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000667 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000668
Chris Lattner2cf5f142009-06-22 01:29:09 +0000669 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000670 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000671 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000672}
673
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000674StringRef AsmParser::ParseStringToEndOfStatement() {
675 const char *Start = getTok().getLoc().getPointer();
676
677 while (Lexer.isNot(AsmToken::EndOfStatement) &&
678 Lexer.isNot(AsmToken::Eof))
679 Lex();
680
681 const char *End = getTok().getLoc().getPointer();
682 return StringRef(Start, End - Start);
683}
Chris Lattnerc4193832009-06-22 05:51:26 +0000684
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000685StringRef AsmParser::ParseStringToComma() {
686 const char *Start = getTok().getLoc().getPointer();
687
688 while (Lexer.isNot(AsmToken::EndOfStatement) &&
689 Lexer.isNot(AsmToken::Comma) &&
690 Lexer.isNot(AsmToken::Eof))
691 Lex();
692
693 const char *End = getTok().getLoc().getPointer();
694 return StringRef(Start, End - Start);
695}
696
Chris Lattner74ec1a32009-06-22 06:32:03 +0000697/// ParseParenExpr - Parse a paren expression and return it.
698/// NOTE: This assumes the leading '(' has already been consumed.
699///
700/// parenexpr ::= expr)
701///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000702bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000703 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000704 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000705 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000706 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000707 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000708 return false;
709}
Chris Lattnerc4193832009-06-22 05:51:26 +0000710
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000711/// ParseBracketExpr - Parse a bracket expression and return it.
712/// NOTE: This assumes the leading '[' has already been consumed.
713///
714/// bracketexpr ::= expr]
715///
716bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
717 if (ParseExpression(Res)) return true;
718 if (Lexer.isNot(AsmToken::RBrac))
719 return TokError("expected ']' in brackets expression");
720 EndLoc = Lexer.getLoc();
721 Lex();
722 return false;
723}
724
Chris Lattner74ec1a32009-06-22 06:32:03 +0000725/// ParsePrimaryExpr - Parse a primary expression and return it.
726/// primaryexpr ::= (parenexpr
727/// primaryexpr ::= symbol
728/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000729/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000730/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000731bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000732 switch (Lexer.getKind()) {
733 default:
734 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000735 // If we have an error assume that we've already handled it.
736 case AsmToken::Error:
737 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000738 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000739 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000740 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000741 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000742 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000743 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000744 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000745 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000746 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000747 EndLoc = Lexer.getLoc();
748
749 StringRef Identifier;
750 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000751 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000752
Daniel Dunbarfffff912009-10-16 01:34:54 +0000753 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000754 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000755 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000756
757 // Lookup the symbol variant if used.
758 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000759 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000760 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000761 if (Variant == MCSymbolRefExpr::VK_Invalid) {
762 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000763 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000764 }
765 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000766
Daniel Dunbarfffff912009-10-16 01:34:54 +0000767 // If this is an absolute variable reference, substitute it now to preserve
768 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000769 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000770 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000771 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000772
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000773 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000774 return false;
775 }
776
777 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000779 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000780 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000781 case AsmToken::Integer: {
782 SMLoc Loc = getTok().getLoc();
783 int64_t IntVal = getTok().getIntVal();
784 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000785 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000786 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000787 // Look for 'b' or 'f' following an Integer as a directional label
788 if (Lexer.getKind() == AsmToken::Identifier) {
789 StringRef IDVal = getTok().getString();
790 if (IDVal == "f" || IDVal == "b"){
791 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
792 IDVal == "f" ? 1 : 0);
793 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
794 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000795 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000796 return Error(Loc, "invalid reference to undefined symbol");
797 EndLoc = Lexer.getLoc();
798 Lex(); // Eat identifier.
799 }
800 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000801 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000802 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000803 case AsmToken::Real: {
804 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000805 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000806 Res = MCConstantExpr::Create(IntVal, getContext());
807 Lex(); // Eat token.
808 return false;
809 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000810 case AsmToken::Dot: {
811 // This is a '.' reference, which references the current PC. Emit a
812 // temporary label to the streamer and refer to it.
813 MCSymbol *Sym = Ctx.CreateTempSymbol();
814 Out.EmitLabel(Sym);
815 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
816 EndLoc = Lexer.getLoc();
817 Lex(); // Eat identifier.
818 return false;
819 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000820 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000821 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000822 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000823 case AsmToken::LBrac:
824 if (!PlatformParser->HasBracketExpressions())
825 return TokError("brackets expression not supported on this target");
826 Lex(); // Eat the '['.
827 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000828 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000829 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000830 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000831 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000832 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000833 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000834 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000835 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000836 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000837 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000838 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000839 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000840 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000841 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000842 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000843 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000844 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000845 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000846 }
847}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000848
Chris Lattnerb4307b32010-01-15 19:28:38 +0000849bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000850 SMLoc EndLoc;
851 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000852}
853
Daniel Dunbarcceba832010-09-17 02:47:07 +0000854const MCExpr *
855AsmParser::ApplyModifierToExpr(const MCExpr *E,
856 MCSymbolRefExpr::VariantKind Variant) {
857 // Recurse over the given expression, rebuilding it to apply the given variant
858 // if there is exactly one symbol.
859 switch (E->getKind()) {
860 case MCExpr::Target:
861 case MCExpr::Constant:
862 return 0;
863
864 case MCExpr::SymbolRef: {
865 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
866
867 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
868 TokError("invalid variant on expression '" +
869 getTok().getIdentifier() + "' (already modified)");
870 return E;
871 }
872
873 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
874 }
875
876 case MCExpr::Unary: {
877 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
878 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
879 if (!Sub)
880 return 0;
881 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
882 }
883
884 case MCExpr::Binary: {
885 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
886 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
887 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
888
889 if (!LHS && !RHS)
890 return 0;
891
892 if (!LHS) LHS = BE->getLHS();
893 if (!RHS) RHS = BE->getRHS();
894
895 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
896 }
897 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000898
Craig Topper85814382012-02-07 05:05:23 +0000899 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000900}
901
Chris Lattner74ec1a32009-06-22 06:32:03 +0000902/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000903///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000904/// expr ::= expr &&,|| expr -> lowest.
905/// expr ::= expr |,^,&,! expr
906/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
907/// expr ::= expr <<,>> expr
908/// expr ::= expr +,- expr
909/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000910/// expr ::= primaryexpr
911///
Chris Lattner54482b42010-01-15 19:39:23 +0000912bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000913 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000914 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000915 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
916 return true;
917
Daniel Dunbarcceba832010-09-17 02:47:07 +0000918 // As a special case, we support 'a op b @ modifier' by rewriting the
919 // expression to include the modifier. This is inefficient, but in general we
920 // expect users to use 'a@modifier op b'.
921 if (Lexer.getKind() == AsmToken::At) {
922 Lex();
923
924 if (Lexer.isNot(AsmToken::Identifier))
925 return TokError("unexpected symbol modifier following '@'");
926
927 MCSymbolRefExpr::VariantKind Variant =
928 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
929 if (Variant == MCSymbolRefExpr::VK_Invalid)
930 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
931
932 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
933 if (!ModifiedRes) {
934 return TokError("invalid modifier '" + getTok().getIdentifier() +
935 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000936 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000937
Daniel Dunbarcceba832010-09-17 02:47:07 +0000938 Res = ModifiedRes;
939 Lex();
940 }
941
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000942 // Try to constant fold it up front, if possible.
943 int64_t Value;
944 if (Res->EvaluateAsAbsolute(Value))
945 Res = MCConstantExpr::Create(Value, getContext());
946
947 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000948}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000949
Chris Lattnerb4307b32010-01-15 19:28:38 +0000950bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000951 Res = 0;
952 return ParseParenExpr(Res, EndLoc) ||
953 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000954}
955
Daniel Dunbar475839e2009-06-29 20:37:27 +0000956bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000957 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000958
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000959 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000960 if (ParseExpression(Expr))
961 return true;
962
Daniel Dunbare00b0112009-10-16 01:57:52 +0000963 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000964 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000965
966 return false;
967}
968
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000969static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000970 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000971 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000972 default:
973 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000974
Jim Grosbachfbe16812011-08-20 16:24:13 +0000975 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000976 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000977 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000978 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000979 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000980 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000981 return 1;
982
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000983
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000984 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000985 //
986 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000987 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000988 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000989 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000990 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000991 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000992 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000993 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000994 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000995 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000996
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000997 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000998 case AsmToken::EqualEqual:
999 Kind = MCBinaryExpr::EQ;
1000 return 3;
1001 case AsmToken::ExclaimEqual:
1002 case AsmToken::LessGreater:
1003 Kind = MCBinaryExpr::NE;
1004 return 3;
1005 case AsmToken::Less:
1006 Kind = MCBinaryExpr::LT;
1007 return 3;
1008 case AsmToken::LessEqual:
1009 Kind = MCBinaryExpr::LTE;
1010 return 3;
1011 case AsmToken::Greater:
1012 Kind = MCBinaryExpr::GT;
1013 return 3;
1014 case AsmToken::GreaterEqual:
1015 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001016 return 3;
1017
Jim Grosbachfbe16812011-08-20 16:24:13 +00001018 // Intermediate Precedence: <<, >>
1019 case AsmToken::LessLess:
1020 Kind = MCBinaryExpr::Shl;
1021 return 4;
1022 case AsmToken::GreaterGreater:
1023 Kind = MCBinaryExpr::Shr;
1024 return 4;
1025
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001026 // High Intermediate Precedence: +, -
1027 case AsmToken::Plus:
1028 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001029 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001030 case AsmToken::Minus:
1031 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001032 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001033
Jim Grosbachfbe16812011-08-20 16:24:13 +00001034 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001035 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001036 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001037 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001038 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001039 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001040 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001041 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001042 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001043 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001044 }
1045}
1046
1047
1048/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1049/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001050bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1051 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001052 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001053 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001054 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001055
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001056 // If the next token is lower precedence than we are allowed to eat, return
1057 // successfully with what we ate already.
1058 if (TokPrec < Precedence)
1059 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001060
Sean Callanan79ed1a82010-01-19 20:22:31 +00001061 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001062
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001063 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001064 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001065 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001066
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001067 // If BinOp binds less tightly with RHS than the operator after RHS, let
1068 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001069 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001070 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001071 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001072 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001073 }
1074
Daniel Dunbar475839e2009-06-29 20:37:27 +00001075 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001076 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001077 }
1078}
1079
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001080/// ParseStatement:
1081/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001082/// ::= Label* Directive ...Operands... EndOfStatement
1083/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001084bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001085 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001086 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001087 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001088 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001089 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001090
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001091 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001092 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001093 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001094 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001095 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001096 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001097 if (Lexer.is(AsmToken::Hash))
1098 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001099
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001100 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001101 if (Lexer.is(AsmToken::Integer)) {
1102 LocalLabelVal = getTok().getIntVal();
1103 if (LocalLabelVal < 0) {
1104 if (!TheCondState.Ignore)
1105 return TokError("unexpected token at start of statement");
1106 IDVal = "";
1107 }
1108 else {
1109 IDVal = getTok().getString();
1110 Lex(); // Consume the integer token to be used as an identifier token.
1111 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001112 if (!TheCondState.Ignore)
1113 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001114 }
1115 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001116
1117 } else if (Lexer.is(AsmToken::Dot)) {
1118 // Treat '.' as a valid identifier in this context.
1119 Lex();
1120 IDVal = ".";
1121
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001122 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001123 if (!TheCondState.Ignore)
1124 return TokError("unexpected token at start of statement");
1125 IDVal = "";
1126 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001127
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001128
Chris Lattner7834fac2010-04-17 18:14:27 +00001129 // Handle conditional assembly here before checking for skipping. We
1130 // have to do this so that .endif isn't skipped in a ".if 0" block for
1131 // example.
1132 if (IDVal == ".if")
1133 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001134 if (IDVal == ".ifb")
1135 return ParseDirectiveIfb(IDLoc, true);
1136 if (IDVal == ".ifnb")
1137 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001138 if (IDVal == ".ifc")
1139 return ParseDirectiveIfc(IDLoc, true);
1140 if (IDVal == ".ifnc")
1141 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001142 if (IDVal == ".ifdef")
1143 return ParseDirectiveIfdef(IDLoc, true);
1144 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1145 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001146 if (IDVal == ".elseif")
1147 return ParseDirectiveElseIf(IDLoc);
1148 if (IDVal == ".else")
1149 return ParseDirectiveElse(IDLoc);
1150 if (IDVal == ".endif")
1151 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001152
Chris Lattner7834fac2010-04-17 18:14:27 +00001153 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001154 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001155 EatToEndOfStatement();
1156 return false;
1157 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001158
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001159 // FIXME: Recurse on local labels?
1160
1161 // See what kind of statement we have.
1162 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001163 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001164 CheckForValidSection();
1165
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001166 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001167 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001168
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001169 // Diagnose attempt to use '.' as a label.
1170 if (IDVal == ".")
1171 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1172
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001173 // Diagnose attempt to use a variable as a label.
1174 //
1175 // FIXME: Diagnostics. Note the location of the definition as a label.
1176 // FIXME: This doesn't diagnose assignment to a symbol which has been
1177 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001178 MCSymbol *Sym;
1179 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001180 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001181 else
1182 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001183 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001184 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001185
Daniel Dunbar959fd882009-08-26 22:13:22 +00001186 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001187 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001188
Kevin Enderby94c2e852011-12-09 18:09:40 +00001189 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001190 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001191 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001192 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1193 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001194
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001195 // Consume any end of statement token, if present, to avoid spurious
1196 // AddBlankLine calls().
1197 if (Lexer.is(AsmToken::EndOfStatement)) {
1198 Lex();
1199 if (Lexer.is(AsmToken::Eof))
1200 return false;
1201 }
1202
Eli Friedman2128aae2012-10-22 23:58:19 +00001203 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001204 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001205
Daniel Dunbar3f872332009-07-28 16:08:33 +00001206 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001207 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001208 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001209
Nico Weber4c4c7322011-01-28 03:04:41 +00001210 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001211
1212 default: // Normal instruction or directive.
1213 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001214 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001215
1216 // If macros are enabled, check to see if this is a macro instantiation.
1217 if (MacrosEnabled)
1218 if (const Macro *M = MacroMap.lookup(IDVal))
1219 return HandleMacroEntry(IDVal, IDLoc, M);
1220
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001221 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001222 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001223
1224 // Target hook for parsing target specific directives.
1225 if (!getTargetParser().ParseDirective(ID))
1226 return false;
1227
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001229 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001230 return ParseDirectiveSet(IDVal, true);
1231 if (IDVal == ".equiv")
1232 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001233
Daniel Dunbara0d14262009-06-24 23:30:00 +00001234 // Data directives
1235
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001236 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001237 return ParseDirectiveAscii(IDVal, false);
1238 if (IDVal == ".asciz" || IDVal == ".string")
1239 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001240
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001241 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001242 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001243 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001244 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001245 if (IDVal == ".value")
1246 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001247 if (IDVal == ".2byte")
1248 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001249 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001250 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001251 if (IDVal == ".int")
1252 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001253 if (IDVal == ".4byte")
1254 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001255 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001256 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001257 if (IDVal == ".8byte")
1258 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001259 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001260 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1261 if (IDVal == ".double")
1262 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001263
Eli Friedman5d68ec22010-07-19 04:17:25 +00001264 if (IDVal == ".align") {
1265 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1266 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1267 }
1268 if (IDVal == ".align32") {
1269 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1270 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1271 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001272 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001273 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001274 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001275 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001276 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001277 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001278 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001279 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001280 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001281 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001282 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001283 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1284
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001285 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001286 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001287
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001288 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001289 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001290 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001291 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001292 if (IDVal == ".zero")
1293 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001294
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001295 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001296
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001297 if (IDVal == ".extern") {
1298 EatToEndOfStatement(); // .extern is the default, ignore it.
1299 return false;
1300 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001301 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001302 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001303 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001304 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001306 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001308 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001309 if (IDVal == ".symbol_resolver")
1310 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001311 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001312 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001313 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001314 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001315 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001316 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001317 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001318 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001319 if (IDVal == ".weak_def_can_be_hidden")
1320 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001321
Hans Wennborg5cc64912011-06-18 13:51:54 +00001322 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001323 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001324 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001325 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001326
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001327 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001328 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001329 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001330 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001331 if (IDVal == ".incbin")
1332 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001333
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001334 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001335 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001336
Rafael Espindola761cb062012-06-03 23:57:14 +00001337 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001338 if (IDVal == ".rept")
1339 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001340 if (IDVal == ".irp")
1341 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001342 if (IDVal == ".irpc")
1343 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001344 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001345 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001346
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001347 // Look up the handler in the handler table.
1348 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1349 DirectiveMap.lookup(IDVal);
1350 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001351 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001352
Kevin Enderby9c656452009-09-10 20:51:44 +00001353
Jim Grosbach686c0182012-05-01 18:38:27 +00001354 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001355 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001356
Eli Friedman2128aae2012-10-22 23:58:19 +00001357 // _emit
1358 if (ParsingInlineAsm && IDVal == "_emit")
1359 return ParseDirectiveEmit(IDLoc, Info);
1360
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001361 CheckForValidSection();
1362
Chris Lattnera7f13542010-05-19 23:34:33 +00001363 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001364 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001365 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001366 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001367
Chad Rosier6a020a72012-10-25 20:41:34 +00001368 ParseInstructionInfo IInfo(Info.AsmRewrites);
1369 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1370 IDLoc,Info.ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001371
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001372 // Dump the parsed representation, if requested.
1373 if (getShowParsedOperands()) {
1374 SmallString<256> Str;
1375 raw_svector_ostream OS(Str);
1376 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001377 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001378 if (i != 0)
1379 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001380 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001381 }
1382 OS << "]";
1383
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001384 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001385 }
1386
Kevin Enderby613b7572011-11-01 22:27:22 +00001387 // If we are generating dwarf for assembly source files and the current
1388 // section is the initial text section then generate a .loc directive for
1389 // the instruction.
1390 if (!HadError && getContext().getGenDwarfForAssembly() &&
1391 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001392
1393 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1394
1395 // If we previously parsed a cpp hash file line comment then make sure the
1396 // current Dwarf File is for the CppHashFilename if not then emit the
1397 // Dwarf File table for it and adjust the line number for the .loc.
1398 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1399 getContext().getMCDwarfFiles();
1400 if (CppHashFilename.size() != 0) {
1401 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1402 CppHashFilename)
1403 getStreamer().EmitDwarfFileDirective(
1404 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1405
1406 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CurBuffer);
1407 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1408 }
1409
Kevin Enderby613b7572011-11-01 22:27:22 +00001410 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001411 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001412 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001413 StringRef());
1414 }
1415
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001416 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001417 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001418 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001419 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1420 Info.ParsedOperands,
1421 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001422 ParsingInlineAsm);
1423 }
Chris Lattner98986712010-01-14 22:21:20 +00001424
Chris Lattnercbf8a982010-09-11 16:18:25 +00001425 // Don't skip the rest of the line, the instruction parser is responsible for
1426 // that.
1427 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001428}
Chris Lattner9a023f72009-06-24 04:43:34 +00001429
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001430/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1431/// since they may not be able to be tokenized to get to the end of line token.
1432void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001433 if (!Lexer.is(AsmToken::EndOfStatement))
1434 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001435 // Eat EOL.
1436 Lex();
1437}
1438
1439/// ParseCppHashLineFilenameComment as this:
1440/// ::= # number "filename"
1441/// or just as a full line comment if it doesn't have a number and a string.
1442bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1443 Lex(); // Eat the hash token.
1444
1445 if (getLexer().isNot(AsmToken::Integer)) {
1446 // Consume the line since in cases it is not a well-formed line directive,
1447 // as if were simply a full line comment.
1448 EatToEndOfLine();
1449 return false;
1450 }
1451
1452 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001453 Lex();
1454
1455 if (getLexer().isNot(AsmToken::String)) {
1456 EatToEndOfLine();
1457 return false;
1458 }
1459
1460 StringRef Filename = getTok().getString();
1461 // Get rid of the enclosing quotes.
1462 Filename = Filename.substr(1, Filename.size()-2);
1463
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001464 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1465 CppHashLoc = L;
1466 CppHashFilename = Filename;
1467 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001468
1469 // Ignore any trailing characters, they're just comment.
1470 EatToEndOfLine();
1471 return false;
1472}
1473
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001474/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001475/// for the Filename and LineNo if any in the diagnostic.
1476void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1477 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1478 raw_ostream &OS = errs();
1479
1480 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1481 const SMLoc &DiagLoc = Diag.getLoc();
1482 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1483 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1484
1485 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1486 // before printing the message.
1487 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001488 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001489 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1490 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1491 }
1492
1493 // If we have not parsed a cpp hash line filename comment or the source
1494 // manager changed or buffer changed (like in a nested include) then just
1495 // print the normal diagnostic using its Filename and LineNo.
1496 if (!Parser->CppHashLineNumber ||
1497 &DiagSrcMgr != &Parser->SrcMgr ||
1498 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001499 if (Parser->SavedDiagHandler)
1500 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1501 else
1502 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001503 return;
1504 }
1505
1506 // Use the CppHashFilename and calculate a line number based on the
1507 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1508 // the diagnostic.
1509 const std::string Filename = Parser->CppHashFilename;
1510
1511 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1512 int CppHashLocLineNo =
1513 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1514 int LineNo = Parser->CppHashLineNumber - 1 +
1515 (DiagLocLineNo - CppHashLocLineNo);
1516
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001517 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1518 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001519 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001520 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001521
Benjamin Kramer04a04262011-10-16 10:48:29 +00001522 if (Parser->SavedDiagHandler)
1523 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1524 else
1525 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001526}
1527
Rafael Espindola799aacf2012-08-21 18:29:30 +00001528// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1529// difference being that that function accepts '@' as part of identifiers and
1530// we can't do that. AsmLexer.cpp should probably be changed to handle
1531// '@' as a special case when needed.
1532static bool isIdentifierChar(char c) {
1533 return isalnum(c) || c == '_' || c == '$' || c == '.';
1534}
1535
Rafael Espindola761cb062012-06-03 23:57:14 +00001536bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001537 const MacroParameters &Parameters,
1538 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001539 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001540 unsigned NParameters = Parameters.size();
1541 if (NParameters != 0 && NParameters != A.size())
1542 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001543
Preston Gurd7b6f2032012-09-19 20:36:12 +00001544 // A macro without parameters is handled differently on Darwin:
1545 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001546 while (!Body.empty()) {
1547 // Scan for the next substitution.
1548 std::size_t End = Body.size(), Pos = 0;
1549 for (; Pos != End; ++Pos) {
1550 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001551 if (!NParameters) {
1552 // This macro has no parameters, look for $0, $1, etc.
1553 if (Body[Pos] != '$' || Pos + 1 == End)
1554 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001555
Rafael Espindola65366442011-06-05 02:43:45 +00001556 char Next = Body[Pos + 1];
1557 if (Next == '$' || Next == 'n' || isdigit(Next))
1558 break;
1559 } else {
1560 // This macro has parameters, look for \foo, \bar, etc.
1561 if (Body[Pos] == '\\' && Pos + 1 != End)
1562 break;
1563 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001564 }
1565
1566 // Add the prefix.
1567 OS << Body.slice(0, Pos);
1568
1569 // Check if we reached the end.
1570 if (Pos == End)
1571 break;
1572
Rafael Espindola65366442011-06-05 02:43:45 +00001573 if (!NParameters) {
1574 switch (Body[Pos+1]) {
1575 // $$ => $
1576 case '$':
1577 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001578 break;
1579
Rafael Espindola65366442011-06-05 02:43:45 +00001580 // $n => number of arguments
1581 case 'n':
1582 OS << A.size();
1583 break;
1584
1585 // $[0-9] => argument
1586 default: {
1587 // Missing arguments are ignored.
1588 unsigned Index = Body[Pos+1] - '0';
1589 if (Index >= A.size())
1590 break;
1591
1592 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001593 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001594 ie = A[Index].end(); it != ie; ++it)
1595 OS << it->getString();
1596 break;
1597 }
1598 }
1599 Pos += 2;
1600 } else {
1601 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001602 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001603 ++I;
1604
1605 const char *Begin = Body.data() + Pos +1;
1606 StringRef Argument(Begin, I - (Pos +1));
1607 unsigned Index = 0;
1608 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001609 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001610 break;
1611
Preston Gurd7b6f2032012-09-19 20:36:12 +00001612 if (Index == NParameters) {
1613 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1614 Pos += 3;
1615 else {
1616 OS << '\\' << Argument;
1617 Pos = I;
1618 }
1619 } else {
1620 for (MacroArgument::const_iterator it = A[Index].begin(),
1621 ie = A[Index].end(); it != ie; ++it)
1622 if (it->getKind() == AsmToken::String)
1623 OS << it->getStringContents();
1624 else
1625 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001626
Preston Gurd7b6f2032012-09-19 20:36:12 +00001627 Pos += 1 + Argument.size();
1628 }
Rafael Espindola65366442011-06-05 02:43:45 +00001629 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001630 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001631 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001632 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001633
Rafael Espindola65366442011-06-05 02:43:45 +00001634 return false;
1635}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001636
Rafael Espindola65366442011-06-05 02:43:45 +00001637MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1638 MemoryBuffer *I)
1639 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1640{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001641}
1642
Preston Gurd7b6f2032012-09-19 20:36:12 +00001643static bool IsOperator(AsmToken::TokenKind kind)
1644{
1645 switch (kind)
1646 {
1647 default:
1648 return false;
1649 case AsmToken::Plus:
1650 case AsmToken::Minus:
1651 case AsmToken::Tilde:
1652 case AsmToken::Slash:
1653 case AsmToken::Star:
1654 case AsmToken::Dot:
1655 case AsmToken::Equal:
1656 case AsmToken::EqualEqual:
1657 case AsmToken::Pipe:
1658 case AsmToken::PipePipe:
1659 case AsmToken::Caret:
1660 case AsmToken::Amp:
1661 case AsmToken::AmpAmp:
1662 case AsmToken::Exclaim:
1663 case AsmToken::ExclaimEqual:
1664 case AsmToken::Percent:
1665 case AsmToken::Less:
1666 case AsmToken::LessEqual:
1667 case AsmToken::LessLess:
1668 case AsmToken::LessGreater:
1669 case AsmToken::Greater:
1670 case AsmToken::GreaterEqual:
1671 case AsmToken::GreaterGreater:
1672 return true;
1673 }
1674}
1675
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001676/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1677/// This is used for both default macro parameter values and the
1678/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001679bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1680 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001681 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001682 unsigned AddTokens = 0;
1683
1684 // gas accepts arguments separated by whitespace, except on Darwin
1685 if (!IsDarwin)
1686 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001687
1688 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001689 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1690 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001691 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001692 }
1693
1694 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1695 // Spaces and commas cannot be mixed to delimit parameters
1696 if (ArgumentDelimiter == AsmToken::Eof)
1697 ArgumentDelimiter = AsmToken::Comma;
1698 else if (ArgumentDelimiter != AsmToken::Comma) {
1699 Lexer.setSkipSpace(true);
1700 return TokError("expected ' ' for macro argument separator");
1701 }
1702 break;
1703 }
1704
1705 if (Lexer.is(AsmToken::Space)) {
1706 Lex(); // Eat spaces
1707
1708 // Spaces can delimit parameters, but could also be part an expression.
1709 // If the token after a space is an operator, add the token and the next
1710 // one into this argument
1711 if (ArgumentDelimiter == AsmToken::Space ||
1712 ArgumentDelimiter == AsmToken::Eof) {
1713 if (IsOperator(Lexer.getKind())) {
1714 // Check to see whether the token is used as an operator,
1715 // or part of an identifier
1716 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1717 if (*NextChar == ' ')
1718 AddTokens = 2;
1719 }
1720
1721 if (!AddTokens && ParenLevel == 0) {
1722 if (ArgumentDelimiter == AsmToken::Eof &&
1723 !IsOperator(Lexer.getKind()))
1724 ArgumentDelimiter = AsmToken::Space;
1725 break;
1726 }
1727 }
1728 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001729
1730 // HandleMacroEntry relies on not advancing the lexer here
1731 // to be able to fill in the remaining default parameter values
1732 if (Lexer.is(AsmToken::EndOfStatement))
1733 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001734
1735 // Adjust the current parentheses level.
1736 if (Lexer.is(AsmToken::LParen))
1737 ++ParenLevel;
1738 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1739 --ParenLevel;
1740
1741 // Append the token to the current argument list.
1742 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001743 if (AddTokens)
1744 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001745 Lex();
1746 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001747
1748 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001749 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001750 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001751 return false;
1752}
1753
1754// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001755bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001756 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001757 // Argument delimiter is initially unknown. It will be set by
1758 // ParseMacroArgument()
1759 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001760
1761 // Parse two kinds of macro invocations:
1762 // - macros defined without any parameters accept an arbitrary number of them
1763 // - macros defined with parameters accept at most that many of them
1764 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1765 ++Parameter) {
1766 MacroArgument MA;
1767
Preston Gurd7b6f2032012-09-19 20:36:12 +00001768 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001769 return true;
1770
Preston Gurd6c9176a2012-09-19 20:29:04 +00001771 if (!MA.empty() || !NParameters)
1772 A.push_back(MA);
1773 else if (NParameters) {
1774 if (!M->Parameters[Parameter].second.empty())
1775 A.push_back(M->Parameters[Parameter].second);
1776 }
Jim Grosbach97146442012-07-30 22:44:17 +00001777
Preston Gurd6c9176a2012-09-19 20:29:04 +00001778 // At the end of the statement, fill in remaining arguments that have
1779 // default values. If there aren't any, then the next argument is
1780 // required but missing
1781 if (Lexer.is(AsmToken::EndOfStatement)) {
1782 if (NParameters && Parameter < NParameters - 1) {
1783 if (M->Parameters[Parameter + 1].second.empty())
1784 return TokError("macro argument '" +
1785 Twine(M->Parameters[Parameter + 1].first) +
1786 "' is missing");
1787 else
1788 continue;
1789 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001790 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001791 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001792
1793 if (Lexer.is(AsmToken::Comma))
1794 Lex();
1795 }
1796 return TokError("Too many arguments");
1797}
1798
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001799bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1800 const Macro *M) {
1801 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1802 // this, although we should protect against infinite loops.
1803 if (ActiveMacros.size() == 20)
1804 return TokError("macros cannot be nested more than 20 levels deep");
1805
Rafael Espindola8a403d32012-08-08 14:51:03 +00001806 MacroArguments A;
1807 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001808 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001809
Jim Grosbach97146442012-07-30 22:44:17 +00001810 // Remove any trailing empty arguments. Do this after-the-fact as we have
1811 // to keep empty arguments in the middle of the list or positionality
1812 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001813 while (!A.empty() && A.back().empty())
1814 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001815
Rafael Espindola65366442011-06-05 02:43:45 +00001816 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1817 // to hold the macro body with substitutions.
1818 SmallString<256> Buf;
1819 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001820 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001821
Rafael Espindola8a403d32012-08-08 14:51:03 +00001822 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001823 return true;
1824
Rafael Espindola761cb062012-06-03 23:57:14 +00001825 // We include the .endmacro in the buffer as our queue to exit the macro
1826 // instantiation.
1827 OS << ".endmacro\n";
1828
Rafael Espindola65366442011-06-05 02:43:45 +00001829 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001830 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001831
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001832 // Create the macro instantiation object and add to the current macro
1833 // instantiation stack.
1834 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001835 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001836 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001837 ActiveMacros.push_back(MI);
1838
1839 // Jump to the macro instantiation and prime the lexer.
1840 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1841 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1842 Lex();
1843
1844 return false;
1845}
1846
1847void AsmParser::HandleMacroExit() {
1848 // Jump to the EndOfStatement we should return to, and consume it.
1849 JumpToLoc(ActiveMacros.back()->ExitLoc);
1850 Lex();
1851
1852 // Pop the instantiation entry.
1853 delete ActiveMacros.back();
1854 ActiveMacros.pop_back();
1855}
1856
Rafael Espindolae71cc862012-01-28 05:57:00 +00001857static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001858 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001859 case MCExpr::Binary: {
1860 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1861 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001862 break;
1863 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001864 case MCExpr::Target:
1865 case MCExpr::Constant:
1866 return false;
1867 case MCExpr::SymbolRef: {
1868 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001869 if (S.isVariable())
1870 return IsUsedIn(Sym, S.getVariableValue());
1871 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001872 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001873 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001874 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001875 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001876
1877 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001878}
1879
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001880bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1881 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001882 // FIXME: Use better location, we should use proper tokens.
1883 SMLoc EqualLoc = Lexer.getLoc();
1884
Daniel Dunbar821e3332009-08-31 08:09:28 +00001885 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001886 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001887 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001888
Rafael Espindolae71cc862012-01-28 05:57:00 +00001889 // Note: we don't count b as used in "a = b". This is to allow
1890 // a = b
1891 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001892
Daniel Dunbar3f872332009-07-28 16:08:33 +00001893 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001894 return TokError("unexpected token in assignment");
1895
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001896 // Error on assignment to '.'.
1897 if (Name == ".") {
1898 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1899 "(use '.space' or '.org').)"));
1900 }
1901
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001902 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001903 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001904
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001905 // Validate that the LHS is allowed to be a variable (either it has not been
1906 // used as a symbol, or it is an absolute symbol).
1907 MCSymbol *Sym = getContext().LookupSymbol(Name);
1908 if (Sym) {
1909 // Diagnose assignment to a label.
1910 //
1911 // FIXME: Diagnostics. Note the location of the definition as a label.
1912 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001913 if (IsUsedIn(Sym, Value))
1914 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1915 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001916 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001917 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1918 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001919 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001920 return Error(EqualLoc, "redefinition of '" + Name + "'");
1921 else if (!Sym->isVariable())
1922 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001923 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001924 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1925 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001926
1927 // Don't count these checks as uses.
1928 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001929 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001930 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001931
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001932 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001933
1934 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001935 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001936 if (NoDeadStrip)
1937 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1938
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001939
1940 return false;
1941}
1942
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001943/// ParseIdentifier:
1944/// ::= identifier
1945/// ::= string
1946bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001947 // The assembler has relaxed rules for accepting identifiers, in particular we
1948 // allow things like '.globl $foo', which would normally be separate
1949 // tokens. At this level, we have already lexed so we cannot (currently)
1950 // handle this as a context dependent token, instead we detect adjacent tokens
1951 // and return the combined identifier.
1952 if (Lexer.is(AsmToken::Dollar)) {
1953 SMLoc DollarLoc = getLexer().getLoc();
1954
1955 // Consume the dollar sign, and check for a following identifier.
1956 Lex();
1957 if (Lexer.isNot(AsmToken::Identifier))
1958 return true;
1959
1960 // We have a '$' followed by an identifier, make sure they are adjacent.
1961 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1962 return true;
1963
1964 // Construct the joined identifier and consume the token.
1965 Res = StringRef(DollarLoc.getPointer(),
1966 getTok().getIdentifier().size() + 1);
1967 Lex();
1968 return false;
1969 }
1970
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001971 if (Lexer.isNot(AsmToken::Identifier) &&
1972 Lexer.isNot(AsmToken::String))
1973 return true;
1974
Sean Callanan18b83232010-01-19 21:44:56 +00001975 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001976
Sean Callanan79ed1a82010-01-19 20:22:31 +00001977 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001978
1979 return false;
1980}
1981
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001982/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001983/// ::= .equ identifier ',' expression
1984/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001985/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001986bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001987 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001988
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001989 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001990 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001991
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001992 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001993 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001994 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001995
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001996 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001997}
1998
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001999bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002000 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002001
2002 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002003 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002004 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2005 if (Str[i] != '\\') {
2006 Data += Str[i];
2007 continue;
2008 }
2009
2010 // Recognize escaped characters. Note that this escape semantics currently
2011 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2012 ++i;
2013 if (i == e)
2014 return TokError("unexpected backslash at end of string");
2015
2016 // Recognize octal sequences.
2017 if ((unsigned) (Str[i] - '0') <= 7) {
2018 // Consume up to three octal characters.
2019 unsigned Value = Str[i] - '0';
2020
2021 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2022 ++i;
2023 Value = Value * 8 + (Str[i] - '0');
2024
2025 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2026 ++i;
2027 Value = Value * 8 + (Str[i] - '0');
2028 }
2029 }
2030
2031 if (Value > 255)
2032 return TokError("invalid octal escape sequence (out of range)");
2033
2034 Data += (unsigned char) Value;
2035 continue;
2036 }
2037
2038 // Otherwise recognize individual escapes.
2039 switch (Str[i]) {
2040 default:
2041 // Just reject invalid escape sequences for now.
2042 return TokError("invalid escape sequence (unrecognized character)");
2043
2044 case 'b': Data += '\b'; break;
2045 case 'f': Data += '\f'; break;
2046 case 'n': Data += '\n'; break;
2047 case 'r': Data += '\r'; break;
2048 case 't': Data += '\t'; break;
2049 case '"': Data += '"'; break;
2050 case '\\': Data += '\\'; break;
2051 }
2052 }
2053
2054 return false;
2055}
2056
Daniel Dunbara0d14262009-06-24 23:30:00 +00002057/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002058/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2059bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002060 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002061 CheckForValidSection();
2062
Daniel Dunbara0d14262009-06-24 23:30:00 +00002063 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002064 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002065 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002066
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002067 std::string Data;
2068 if (ParseEscapedString(Data))
2069 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002070
2071 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002072 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002073 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2074
Sean Callanan79ed1a82010-01-19 20:22:31 +00002075 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002076
2077 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002078 break;
2079
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002080 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002081 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002082 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002083 }
2084 }
2085
Sean Callanan79ed1a82010-01-19 20:22:31 +00002086 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002087 return false;
2088}
2089
2090/// ParseDirectiveValue
2091/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2092bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002093 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002094 CheckForValidSection();
2095
Daniel Dunbara0d14262009-06-24 23:30:00 +00002096 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002097 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002098 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002099 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002100 return true;
2101
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002102 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002103 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2104 assert(Size <= 8 && "Invalid size");
2105 uint64_t IntValue = MCE->getValue();
2106 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2107 return Error(ExprLoc, "literal value out of range for directive");
2108 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2109 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002110 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002111
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002112 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002113 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002114
Daniel Dunbara0d14262009-06-24 23:30:00 +00002115 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002116 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002117 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002118 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002119 }
2120 }
2121
Sean Callanan79ed1a82010-01-19 20:22:31 +00002122 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002123 return false;
2124}
2125
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002126/// ParseDirectiveRealValue
2127/// ::= (.single | .double) [ expression (, expression)* ]
2128bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2129 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2130 CheckForValidSection();
2131
2132 for (;;) {
2133 // We don't truly support arithmetic on floating point expressions, so we
2134 // have to manually parse unary prefixes.
2135 bool IsNeg = false;
2136 if (getLexer().is(AsmToken::Minus)) {
2137 Lex();
2138 IsNeg = true;
2139 } else if (getLexer().is(AsmToken::Plus))
2140 Lex();
2141
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002142 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002143 getLexer().isNot(AsmToken::Real) &&
2144 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002145 return TokError("unexpected token in directive");
2146
2147 // Convert to an APFloat.
2148 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002149 StringRef IDVal = getTok().getString();
2150 if (getLexer().is(AsmToken::Identifier)) {
2151 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2152 Value = APFloat::getInf(Semantics);
2153 else if (!IDVal.compare_lower("nan"))
2154 Value = APFloat::getNaN(Semantics, false, ~0);
2155 else
2156 return TokError("invalid floating point literal");
2157 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002158 APFloat::opInvalidOp)
2159 return TokError("invalid floating point literal");
2160 if (IsNeg)
2161 Value.changeSign();
2162
2163 // Consume the numeric token.
2164 Lex();
2165
2166 // Emit the value as an integer.
2167 APInt AsInt = Value.bitcastToAPInt();
2168 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2169 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2170
2171 if (getLexer().is(AsmToken::EndOfStatement))
2172 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002173
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002174 if (getLexer().isNot(AsmToken::Comma))
2175 return TokError("unexpected token in directive");
2176 Lex();
2177 }
2178 }
2179
2180 Lex();
2181 return false;
2182}
2183
Daniel Dunbara0d14262009-06-24 23:30:00 +00002184/// ParseDirectiveSpace
2185/// ::= .space expression [ , expression ]
2186bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002187 CheckForValidSection();
2188
Daniel Dunbara0d14262009-06-24 23:30:00 +00002189 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002190 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191 return true;
2192
2193 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002194 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2195 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002196 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002197 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002198
Daniel Dunbar475839e2009-06-29 20:37:27 +00002199 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002200 return true;
2201
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002202 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002203 return TokError("unexpected token in '.space' directive");
2204 }
2205
Sean Callanan79ed1a82010-01-19 20:22:31 +00002206 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002207
2208 if (NumBytes <= 0)
2209 return TokError("invalid number of bytes in '.space' directive");
2210
2211 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002212 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002213
2214 return false;
2215}
2216
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002217/// ParseDirectiveZero
2218/// ::= .zero expression
2219bool AsmParser::ParseDirectiveZero() {
2220 CheckForValidSection();
2221
2222 int64_t NumBytes;
2223 if (ParseAbsoluteExpression(NumBytes))
2224 return true;
2225
Rafael Espindolae452b172010-10-05 19:42:57 +00002226 int64_t Val = 0;
2227 if (getLexer().is(AsmToken::Comma)) {
2228 Lex();
2229 if (ParseAbsoluteExpression(Val))
2230 return true;
2231 }
2232
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002233 if (getLexer().isNot(AsmToken::EndOfStatement))
2234 return TokError("unexpected token in '.zero' directive");
2235
2236 Lex();
2237
Rafael Espindolae452b172010-10-05 19:42:57 +00002238 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002239
2240 return false;
2241}
2242
Daniel Dunbara0d14262009-06-24 23:30:00 +00002243/// ParseDirectiveFill
2244/// ::= .fill expression , expression , expression
2245bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002246 CheckForValidSection();
2247
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002249 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002250 return true;
2251
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002252 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002253 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002254 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002255
Daniel Dunbara0d14262009-06-24 23:30:00 +00002256 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002257 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002258 return true;
2259
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002260 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002261 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002262 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002263
Daniel Dunbara0d14262009-06-24 23:30:00 +00002264 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002265 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002266 return true;
2267
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002268 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002270
Sean Callanan79ed1a82010-01-19 20:22:31 +00002271 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002272
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002273 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2274 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002275
2276 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002277 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002278
2279 return false;
2280}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002281
2282/// ParseDirectiveOrg
2283/// ::= .org expression [ , expression ]
2284bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002285 CheckForValidSection();
2286
Daniel Dunbar821e3332009-08-31 08:09:28 +00002287 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002288 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002289 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002290 return true;
2291
2292 // Parse optional fill expression.
2293 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002294 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2295 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002296 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002297 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002298
Daniel Dunbar475839e2009-06-29 20:37:27 +00002299 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002300 return true;
2301
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002302 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002303 return TokError("unexpected token in '.org' directive");
2304 }
2305
Sean Callanan79ed1a82010-01-19 20:22:31 +00002306 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002307
Jim Grosbachebd4c052012-01-27 00:37:08 +00002308 // Only limited forms of relocatable expressions are accepted here, it
2309 // has to be relative to the current section. The streamer will return
2310 // 'true' if the expression wasn't evaluatable.
2311 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2312 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002313
2314 return false;
2315}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002316
2317/// ParseDirectiveAlign
2318/// ::= {.align, ...} expression [ , expression [ , expression ]]
2319bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002320 CheckForValidSection();
2321
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002322 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002323 int64_t Alignment;
2324 if (ParseAbsoluteExpression(Alignment))
2325 return true;
2326
2327 SMLoc MaxBytesLoc;
2328 bool HasFillExpr = false;
2329 int64_t FillExpr = 0;
2330 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002331 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2332 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002333 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002334 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002335
2336 // The fill expression can be omitted while specifying a maximum number of
2337 // alignment bytes, e.g:
2338 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002339 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002340 HasFillExpr = true;
2341 if (ParseAbsoluteExpression(FillExpr))
2342 return true;
2343 }
2344
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002345 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2346 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002347 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002348 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002349
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002350 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002351 if (ParseAbsoluteExpression(MaxBytesToFill))
2352 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002353
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002354 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002355 return TokError("unexpected token in directive");
2356 }
2357 }
2358
Sean Callanan79ed1a82010-01-19 20:22:31 +00002359 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002360
Daniel Dunbar648ac512010-05-17 21:54:30 +00002361 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002362 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002363
2364 // Compute alignment in bytes.
2365 if (IsPow2) {
2366 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002367 if (Alignment >= 32) {
2368 Error(AlignmentLoc, "invalid alignment value");
2369 Alignment = 31;
2370 }
2371
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002372 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002373 }
2374
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002375 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002376 if (MaxBytesLoc.isValid()) {
2377 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002378 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2379 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002380 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002381 }
2382
2383 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002384 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2385 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002386 MaxBytesToFill = 0;
2387 }
2388 }
2389
Daniel Dunbar648ac512010-05-17 21:54:30 +00002390 // Check whether we should use optimal code alignment for this .align
2391 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002392 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002393 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2394 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002395 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002396 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002397 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002398 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2399 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002400 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002401
2402 return false;
2403}
2404
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002405/// ParseDirectiveSymbolAttribute
2406/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002407bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002408 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002409 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002410 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002411 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002412
2413 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002414 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002415
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002416 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002417
Jim Grosbach10ec6502011-09-15 17:56:49 +00002418 // Assembler local symbols don't make any sense here. Complain loudly.
2419 if (Sym->isTemporary())
2420 return Error(Loc, "non-local symbol required in directive");
2421
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002423
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002425 break;
2426
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002427 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002428 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002429 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002430 }
2431 }
2432
Sean Callanan79ed1a82010-01-19 20:22:31 +00002433 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002434 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002435}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002436
2437/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002438/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2439bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002440 CheckForValidSection();
2441
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002442 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002443 StringRef Name;
2444 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002445 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002446
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002447 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002448 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002449
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002450 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002451 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002452 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002453
2454 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002455 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002456 if (ParseAbsoluteExpression(Size))
2457 return true;
2458
2459 int64_t Pow2Alignment = 0;
2460 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002461 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002462 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002463 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002464 if (ParseAbsoluteExpression(Pow2Alignment))
2465 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002466
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002467 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2468 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002469 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2470
Chris Lattner258281d2010-01-19 06:22:22 +00002471 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002472 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2473 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002474 if (!isPowerOf2_64(Pow2Alignment))
2475 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2476 Pow2Alignment = Log2_64(Pow2Alignment);
2477 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002478 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002479
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002480 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002481 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002482
Sean Callanan79ed1a82010-01-19 20:22:31 +00002483 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002484
Chris Lattner1fc3d752009-07-09 17:25:12 +00002485 // NOTE: a size of zero for a .comm should create a undefined symbol
2486 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002487 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002488 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2489 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002490
Eric Christopherc260a3e2010-05-14 01:38:54 +00002491 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002492 // may internally end up wanting an alignment in bytes.
2493 // FIXME: Diagnose overflow.
2494 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002495 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2496 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002497
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002498 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002499 return Error(IDLoc, "invalid symbol redefinition");
2500
Chris Lattner1fc3d752009-07-09 17:25:12 +00002501 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002502 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002503 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002504 return false;
2505 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002506
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002507 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002508 return false;
2509}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002510
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002511/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002512/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002513bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002514 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002515 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002516
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002517 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002518 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002519 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002520
Sean Callanan79ed1a82010-01-19 20:22:31 +00002521 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002522
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002523 if (Str.empty())
2524 Error(Loc, ".abort detected. Assembly stopping.");
2525 else
2526 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002527 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002528
2529 return false;
2530}
Kevin Enderby71148242009-07-14 21:35:03 +00002531
Kevin Enderby1f049b22009-07-14 23:21:55 +00002532/// ParseDirectiveInclude
2533/// ::= .include "filename"
2534bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002535 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002536 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002537
Sean Callanan18b83232010-01-19 21:44:56 +00002538 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002539 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002540 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002541
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002542 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002543 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002544
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002545 // Strip the quotes.
2546 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002547
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002548 // Attempt to switch the lexer to the included file before consuming the end
2549 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002550 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002551 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002552 return true;
2553 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002554
2555 return false;
2556}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002557
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002558/// ParseDirectiveIncbin
2559/// ::= .incbin "filename"
2560bool AsmParser::ParseDirectiveIncbin() {
2561 if (getLexer().isNot(AsmToken::String))
2562 return TokError("expected string in '.incbin' directive");
2563
2564 std::string Filename = getTok().getString();
2565 SMLoc IncbinLoc = getLexer().getLoc();
2566 Lex();
2567
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '.incbin' directive");
2570
2571 // Strip the quotes.
2572 Filename = Filename.substr(1, Filename.size()-2);
2573
2574 // Attempt to process the included file.
2575 if (ProcessIncbinFile(Filename)) {
2576 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2577 return true;
2578 }
2579
2580 return false;
2581}
2582
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002583/// ParseDirectiveIf
2584/// ::= .if expression
2585bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002586 TheCondStack.push_back(TheCondState);
2587 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002588 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002589 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002590 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002591 int64_t ExprValue;
2592 if (ParseAbsoluteExpression(ExprValue))
2593 return true;
2594
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002595 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002596 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002597
Sean Callanan79ed1a82010-01-19 20:22:31 +00002598 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002599
2600 TheCondState.CondMet = ExprValue;
2601 TheCondState.Ignore = !TheCondState.CondMet;
2602 }
2603
2604 return false;
2605}
2606
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002607/// ParseDirectiveIfb
2608/// ::= .ifb string
2609bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2610 TheCondStack.push_back(TheCondState);
2611 TheCondState.TheCond = AsmCond::IfCond;
2612
Benjamin Kramer29739e72012-05-12 16:52:21 +00002613 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002614 EatToEndOfStatement();
2615 } else {
2616 StringRef Str = ParseStringToEndOfStatement();
2617
2618 if (getLexer().isNot(AsmToken::EndOfStatement))
2619 return TokError("unexpected token in '.ifb' directive");
2620
2621 Lex();
2622
2623 TheCondState.CondMet = ExpectBlank == Str.empty();
2624 TheCondState.Ignore = !TheCondState.CondMet;
2625 }
2626
2627 return false;
2628}
2629
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002630/// ParseDirectiveIfc
2631/// ::= .ifc string1, string2
2632bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2633 TheCondStack.push_back(TheCondState);
2634 TheCondState.TheCond = AsmCond::IfCond;
2635
Benjamin Kramer29739e72012-05-12 16:52:21 +00002636 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002637 EatToEndOfStatement();
2638 } else {
2639 StringRef Str1 = ParseStringToComma();
2640
2641 if (getLexer().isNot(AsmToken::Comma))
2642 return TokError("unexpected token in '.ifc' directive");
2643
2644 Lex();
2645
2646 StringRef Str2 = ParseStringToEndOfStatement();
2647
2648 if (getLexer().isNot(AsmToken::EndOfStatement))
2649 return TokError("unexpected token in '.ifc' directive");
2650
2651 Lex();
2652
2653 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2654 TheCondState.Ignore = !TheCondState.CondMet;
2655 }
2656
2657 return false;
2658}
2659
2660/// ParseDirectiveIfdef
2661/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002662bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2663 StringRef Name;
2664 TheCondStack.push_back(TheCondState);
2665 TheCondState.TheCond = AsmCond::IfCond;
2666
2667 if (TheCondState.Ignore) {
2668 EatToEndOfStatement();
2669 } else {
2670 if (ParseIdentifier(Name))
2671 return TokError("expected identifier after '.ifdef'");
2672
2673 Lex();
2674
2675 MCSymbol *Sym = getContext().LookupSymbol(Name);
2676
2677 if (expect_defined)
2678 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2679 else
2680 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2681 TheCondState.Ignore = !TheCondState.CondMet;
2682 }
2683
2684 return false;
2685}
2686
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002687/// ParseDirectiveElseIf
2688/// ::= .elseif expression
2689bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2690 if (TheCondState.TheCond != AsmCond::IfCond &&
2691 TheCondState.TheCond != AsmCond::ElseIfCond)
2692 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2693 " an .elseif");
2694 TheCondState.TheCond = AsmCond::ElseIfCond;
2695
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002696 bool LastIgnoreState = false;
2697 if (!TheCondStack.empty())
2698 LastIgnoreState = TheCondStack.back().Ignore;
2699 if (LastIgnoreState || TheCondState.CondMet) {
2700 TheCondState.Ignore = true;
2701 EatToEndOfStatement();
2702 }
2703 else {
2704 int64_t ExprValue;
2705 if (ParseAbsoluteExpression(ExprValue))
2706 return true;
2707
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002708 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002709 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002710
Sean Callanan79ed1a82010-01-19 20:22:31 +00002711 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002712 TheCondState.CondMet = ExprValue;
2713 TheCondState.Ignore = !TheCondState.CondMet;
2714 }
2715
2716 return false;
2717}
2718
2719/// ParseDirectiveElse
2720/// ::= .else
2721bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002722 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002723 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002724
Sean Callanan79ed1a82010-01-19 20:22:31 +00002725 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002726
2727 if (TheCondState.TheCond != AsmCond::IfCond &&
2728 TheCondState.TheCond != AsmCond::ElseIfCond)
2729 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2730 ".elseif");
2731 TheCondState.TheCond = AsmCond::ElseCond;
2732 bool LastIgnoreState = false;
2733 if (!TheCondStack.empty())
2734 LastIgnoreState = TheCondStack.back().Ignore;
2735 if (LastIgnoreState || TheCondState.CondMet)
2736 TheCondState.Ignore = true;
2737 else
2738 TheCondState.Ignore = false;
2739
2740 return false;
2741}
2742
2743/// ParseDirectiveEndIf
2744/// ::= .endif
2745bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002746 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002747 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002748
Sean Callanan79ed1a82010-01-19 20:22:31 +00002749 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002750
2751 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2752 TheCondStack.empty())
2753 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2754 ".else");
2755 if (!TheCondStack.empty()) {
2756 TheCondState = TheCondStack.back();
2757 TheCondStack.pop_back();
2758 }
2759
2760 return false;
2761}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002762
2763/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002764/// ::= .file [number] filename
2765/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002766bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002767 // FIXME: I'm not sure what this is.
2768 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002769 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002770 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002771 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002772 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002773
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002774 if (FileNumber < 1)
2775 return TokError("file number less than one");
2776 }
2777
Daniel Dunbareceec052010-07-12 17:45:27 +00002778 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002779 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002780
Nick Lewycky44d798d2011-10-17 23:05:28 +00002781 // Usually the directory and filename together, otherwise just the directory.
2782 StringRef Path = getTok().getString();
2783 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002784 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002785
Nick Lewycky44d798d2011-10-17 23:05:28 +00002786 StringRef Directory;
2787 StringRef Filename;
2788 if (getLexer().is(AsmToken::String)) {
2789 if (FileNumber == -1)
2790 return TokError("explicit path specified, but no file number");
2791 Filename = getTok().getString();
2792 Filename = Filename.substr(1, Filename.size()-2);
2793 Directory = Path;
2794 Lex();
2795 } else {
2796 Filename = Path;
2797 }
2798
Daniel Dunbareceec052010-07-12 17:45:27 +00002799 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002800 return TokError("unexpected token in '.file' directive");
2801
Chris Lattnerd32e8032010-01-25 19:02:58 +00002802 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002803 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002804 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002805 if (getContext().getGenDwarfForAssembly() == true)
2806 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2807 "used to generate dwarf debug info for assembly code");
2808
Nick Lewycky44d798d2011-10-17 23:05:28 +00002809 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002810 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002811 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002812
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002813 return false;
2814}
2815
2816/// ParseDirectiveLine
2817/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002818bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002819 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2820 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002821 return TokError("unexpected token in '.line' directive");
2822
Sean Callanan18b83232010-01-19 21:44:56 +00002823 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002824 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002825 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002826
2827 // FIXME: Do something with the .line.
2828 }
2829
Daniel Dunbareceec052010-07-12 17:45:27 +00002830 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002831 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002832
2833 return false;
2834}
2835
2836
2837/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002838/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002839/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2840/// The first number is a file number, must have been previously assigned with
2841/// a .file directive, the second number is the line number and optionally the
2842/// third number is a column position (zero if not specified). The remaining
2843/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002844bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002845
Daniel Dunbareceec052010-07-12 17:45:27 +00002846 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002847 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002848 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002849 if (FileNumber < 1)
2850 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002851 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002852 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002853 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002854
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002855 int64_t LineNumber = 0;
2856 if (getLexer().is(AsmToken::Integer)) {
2857 LineNumber = getTok().getIntVal();
2858 if (LineNumber < 1)
2859 return TokError("line number less than one in '.loc' directive");
2860 Lex();
2861 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002862
2863 int64_t ColumnPos = 0;
2864 if (getLexer().is(AsmToken::Integer)) {
2865 ColumnPos = getTok().getIntVal();
2866 if (ColumnPos < 0)
2867 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002868 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002869 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002870
Kevin Enderbyc0957932010-09-30 16:52:03 +00002871 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002872 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002873 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002874 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2875 for (;;) {
2876 if (getLexer().is(AsmToken::EndOfStatement))
2877 break;
2878
2879 StringRef Name;
2880 SMLoc Loc = getTok().getLoc();
2881 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002882 return TokError("unexpected token in '.loc' directive");
2883
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002884 if (Name == "basic_block")
2885 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2886 else if (Name == "prologue_end")
2887 Flags |= DWARF2_FLAG_PROLOGUE_END;
2888 else if (Name == "epilogue_begin")
2889 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2890 else if (Name == "is_stmt") {
2891 SMLoc Loc = getTok().getLoc();
2892 const MCExpr *Value;
2893 if (getParser().ParseExpression(Value))
2894 return true;
2895 // The expression must be the constant 0 or 1.
2896 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2897 int Value = MCE->getValue();
2898 if (Value == 0)
2899 Flags &= ~DWARF2_FLAG_IS_STMT;
2900 else if (Value == 1)
2901 Flags |= DWARF2_FLAG_IS_STMT;
2902 else
2903 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002904 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002905 else {
2906 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2907 }
2908 }
2909 else if (Name == "isa") {
2910 SMLoc Loc = getTok().getLoc();
2911 const MCExpr *Value;
2912 if (getParser().ParseExpression(Value))
2913 return true;
2914 // The expression must be a constant greater or equal to 0.
2915 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2916 int Value = MCE->getValue();
2917 if (Value < 0)
2918 return Error(Loc, "isa number less than zero");
2919 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002920 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002921 else {
2922 return Error(Loc, "isa number not a constant value");
2923 }
2924 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002925 else if (Name == "discriminator") {
2926 if (getParser().ParseAbsoluteExpression(Discriminator))
2927 return true;
2928 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002929 else {
2930 return Error(Loc, "unknown sub-directive in '.loc' directive");
2931 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002932
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002933 if (getLexer().is(AsmToken::EndOfStatement))
2934 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002935 }
2936 }
2937
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002938 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002939 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002940
2941 return false;
2942}
2943
Daniel Dunbar138abae2010-10-16 04:56:42 +00002944/// ParseDirectiveStabs
2945/// ::= .stabs string, number, number, number
2946bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2947 SMLoc DirectiveLoc) {
2948 return TokError("unsupported directive '" + Directive + "'");
2949}
2950
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002951/// ParseDirectiveCFISections
2952/// ::= .cfi_sections section [, section]
2953bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2954 SMLoc DirectiveLoc) {
2955 StringRef Name;
2956 bool EH = false;
2957 bool Debug = false;
2958
2959 if (getParser().ParseIdentifier(Name))
2960 return TokError("Expected an identifier");
2961
2962 if (Name == ".eh_frame")
2963 EH = true;
2964 else if (Name == ".debug_frame")
2965 Debug = true;
2966
2967 if (getLexer().is(AsmToken::Comma)) {
2968 Lex();
2969
2970 if (getParser().ParseIdentifier(Name))
2971 return TokError("Expected an identifier");
2972
2973 if (Name == ".eh_frame")
2974 EH = true;
2975 else if (Name == ".debug_frame")
2976 Debug = true;
2977 }
2978
2979 getStreamer().EmitCFISections(EH, Debug);
2980
2981 return false;
2982}
2983
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002984/// ParseDirectiveCFIStartProc
2985/// ::= .cfi_startproc
2986bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2987 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002988 getStreamer().EmitCFIStartProc();
2989 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002990}
2991
2992/// ParseDirectiveCFIEndProc
2993/// ::= .cfi_endproc
2994bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002995 getStreamer().EmitCFIEndProc();
2996 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002997}
2998
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002999/// ParseRegisterOrRegisterNumber - parse register name or number.
3000bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3001 SMLoc DirectiveLoc) {
3002 unsigned RegNo;
3003
Jim Grosbach6f888a82011-06-02 17:14:04 +00003004 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003005 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3006 DirectiveLoc))
3007 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003008 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003009 } else
3010 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003011
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003012 return false;
3013}
3014
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003015/// ParseDirectiveCFIDefCfa
3016/// ::= .cfi_def_cfa register, offset
3017bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3018 SMLoc DirectiveLoc) {
3019 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003020 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003021 return true;
3022
3023 if (getLexer().isNot(AsmToken::Comma))
3024 return TokError("unexpected token in directive");
3025 Lex();
3026
3027 int64_t Offset = 0;
3028 if (getParser().ParseAbsoluteExpression(Offset))
3029 return true;
3030
Rafael Espindola066c2f42011-04-12 23:59:07 +00003031 getStreamer().EmitCFIDefCfa(Register, Offset);
3032 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003033}
3034
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003035/// ParseDirectiveCFIDefCfaOffset
3036/// ::= .cfi_def_cfa_offset offset
3037bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3038 SMLoc DirectiveLoc) {
3039 int64_t Offset = 0;
3040 if (getParser().ParseAbsoluteExpression(Offset))
3041 return true;
3042
Rafael Espindola066c2f42011-04-12 23:59:07 +00003043 getStreamer().EmitCFIDefCfaOffset(Offset);
3044 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003045}
3046
3047/// ParseDirectiveCFIAdjustCfaOffset
3048/// ::= .cfi_adjust_cfa_offset adjustment
3049bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3050 SMLoc DirectiveLoc) {
3051 int64_t Adjustment = 0;
3052 if (getParser().ParseAbsoluteExpression(Adjustment))
3053 return true;
3054
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003055 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3056 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003057}
3058
3059/// ParseDirectiveCFIDefCfaRegister
3060/// ::= .cfi_def_cfa_register register
3061bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3062 SMLoc DirectiveLoc) {
3063 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003064 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003065 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003066
Rafael Espindola066c2f42011-04-12 23:59:07 +00003067 getStreamer().EmitCFIDefCfaRegister(Register);
3068 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003069}
3070
3071/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003072/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003073bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3074 int64_t Register = 0;
3075 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003076
3077 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003078 return true;
3079
3080 if (getLexer().isNot(AsmToken::Comma))
3081 return TokError("unexpected token in directive");
3082 Lex();
3083
3084 if (getParser().ParseAbsoluteExpression(Offset))
3085 return true;
3086
Rafael Espindola066c2f42011-04-12 23:59:07 +00003087 getStreamer().EmitCFIOffset(Register, Offset);
3088 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003089}
3090
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003091/// ParseDirectiveCFIRelOffset
3092/// ::= .cfi_rel_offset register, offset
3093bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3094 SMLoc DirectiveLoc) {
3095 int64_t Register = 0;
3096
3097 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3098 return true;
3099
3100 if (getLexer().isNot(AsmToken::Comma))
3101 return TokError("unexpected token in directive");
3102 Lex();
3103
3104 int64_t Offset = 0;
3105 if (getParser().ParseAbsoluteExpression(Offset))
3106 return true;
3107
Rafael Espindola25f492e2011-04-12 16:12:03 +00003108 getStreamer().EmitCFIRelOffset(Register, Offset);
3109 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003110}
3111
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003112static bool isValidEncoding(int64_t Encoding) {
3113 if (Encoding & ~0xff)
3114 return false;
3115
3116 if (Encoding == dwarf::DW_EH_PE_omit)
3117 return true;
3118
3119 const unsigned Format = Encoding & 0xf;
3120 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3121 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3122 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3123 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3124 return false;
3125
Rafael Espindolacaf11582010-12-29 04:31:26 +00003126 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003127 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003128 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003129 return false;
3130
3131 return true;
3132}
3133
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003134/// ParseDirectiveCFIPersonalityOrLsda
3135/// ::= .cfi_personality encoding, [symbol_name]
3136/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003137bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003138 SMLoc DirectiveLoc) {
3139 int64_t Encoding = 0;
3140 if (getParser().ParseAbsoluteExpression(Encoding))
3141 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003142 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003143 return false;
3144
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003145 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003146 return TokError("unsupported encoding.");
3147
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003148 if (getLexer().isNot(AsmToken::Comma))
3149 return TokError("unexpected token in directive");
3150 Lex();
3151
3152 StringRef Name;
3153 if (getParser().ParseIdentifier(Name))
3154 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003155
3156 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3157
3158 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003159 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003160 else {
3161 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003162 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003163 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003164 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003165}
3166
Rafael Espindolafe024d02010-12-28 18:36:23 +00003167/// ParseDirectiveCFIRememberState
3168/// ::= .cfi_remember_state
3169bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3170 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003171 getStreamer().EmitCFIRememberState();
3172 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003173}
3174
3175/// ParseDirectiveCFIRestoreState
3176/// ::= .cfi_remember_state
3177bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3178 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003179 getStreamer().EmitCFIRestoreState();
3180 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003181}
3182
Rafael Espindolac5754392011-04-12 15:31:05 +00003183/// ParseDirectiveCFISameValue
3184/// ::= .cfi_same_value register
3185bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3186 SMLoc DirectiveLoc) {
3187 int64_t Register = 0;
3188
3189 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3190 return true;
3191
3192 getStreamer().EmitCFISameValue(Register);
3193
3194 return false;
3195}
3196
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003197/// ParseDirectiveCFIRestore
3198/// ::= .cfi_restore register
3199bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003200 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003201 int64_t Register = 0;
3202 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3203 return true;
3204
3205 getStreamer().EmitCFIRestore(Register);
3206
3207 return false;
3208}
3209
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003210/// ParseDirectiveCFIEscape
3211/// ::= .cfi_escape expression[,...]
3212bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003213 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003214 std::string Values;
3215 int64_t CurrValue;
3216 if (getParser().ParseAbsoluteExpression(CurrValue))
3217 return true;
3218
3219 Values.push_back((uint8_t)CurrValue);
3220
3221 while (getLexer().is(AsmToken::Comma)) {
3222 Lex();
3223
3224 if (getParser().ParseAbsoluteExpression(CurrValue))
3225 return true;
3226
3227 Values.push_back((uint8_t)CurrValue);
3228 }
3229
3230 getStreamer().EmitCFIEscape(Values);
3231 return false;
3232}
3233
Rafael Espindola16d7d432012-01-23 21:51:52 +00003234/// ParseDirectiveCFISignalFrame
3235/// ::= .cfi_signal_frame
3236bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3237 SMLoc DirectiveLoc) {
3238 if (getLexer().isNot(AsmToken::EndOfStatement))
3239 return Error(getLexer().getLoc(),
3240 "unexpected token in '" + Directive + "' directive");
3241
3242 getStreamer().EmitCFISignalFrame();
3243
3244 return false;
3245}
3246
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003247/// ParseDirectiveMacrosOnOff
3248/// ::= .macros_on
3249/// ::= .macros_off
3250bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3251 SMLoc DirectiveLoc) {
3252 if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return Error(getLexer().getLoc(),
3254 "unexpected token in '" + Directive + "' directive");
3255
3256 getParser().MacrosEnabled = Directive == ".macros_on";
3257
3258 return false;
3259}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003260
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003261/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003262/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003263bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3264 SMLoc DirectiveLoc) {
3265 StringRef Name;
3266 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003267 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003268
Rafael Espindola8a403d32012-08-08 14:51:03 +00003269 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003270 // Argument delimiter is initially unknown. It will be set by
3271 // ParseMacroArgument()
3272 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003273 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003274 for (;;) {
3275 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003276 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003277 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003278
3279 if (getLexer().is(AsmToken::Equal)) {
3280 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003281 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003282 return true;
3283 }
3284
Rafael Espindola65366442011-06-05 02:43:45 +00003285 Parameters.push_back(Parameter);
3286
Preston Gurd7b6f2032012-09-19 20:36:12 +00003287 if (getLexer().is(AsmToken::Comma))
3288 Lex();
3289 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003290 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003291 }
3292 }
3293
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003294 // Eat the end of statement.
3295 Lex();
3296
3297 AsmToken EndToken, StartToken = getTok();
3298
3299 // Lex the macro definition.
3300 for (;;) {
3301 // Check whether we have reached the end of the file.
3302 if (getLexer().is(AsmToken::Eof))
3303 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3304
3305 // Otherwise, check whether we have reach the .endmacro.
3306 if (getLexer().is(AsmToken::Identifier) &&
3307 (getTok().getIdentifier() == ".endm" ||
3308 getTok().getIdentifier() == ".endmacro")) {
3309 EndToken = getTok();
3310 Lex();
3311 if (getLexer().isNot(AsmToken::EndOfStatement))
3312 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3313 "' directive");
3314 break;
3315 }
3316
3317 // Otherwise, scan til the end of the statement.
3318 getParser().EatToEndOfStatement();
3319 }
3320
3321 if (getParser().MacroMap.lookup(Name)) {
3322 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3323 }
3324
3325 const char *BodyStart = StartToken.getLoc().getPointer();
3326 const char *BodyEnd = EndToken.getLoc().getPointer();
3327 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003328 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003329 return false;
3330}
3331
3332/// ParseDirectiveEndMacro
3333/// ::= .endm
3334/// ::= .endmacro
3335bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003336 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003337 if (getLexer().isNot(AsmToken::EndOfStatement))
3338 return TokError("unexpected token in '" + Directive + "' directive");
3339
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003340 // If we are inside a macro instantiation, terminate the current
3341 // instantiation.
3342 if (!getParser().ActiveMacros.empty()) {
3343 getParser().HandleMacroExit();
3344 return false;
3345 }
3346
3347 // Otherwise, this .endmacro is a stray entry in the file; well formed
3348 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003349 return TokError("unexpected '" + Directive + "' in file, "
3350 "no current macro definition");
3351}
3352
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003353/// ParseDirectivePurgeMacro
3354/// ::= .purgem
3355bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3356 SMLoc DirectiveLoc) {
3357 StringRef Name;
3358 if (getParser().ParseIdentifier(Name))
3359 return TokError("expected identifier in '.purgem' directive");
3360
3361 if (getLexer().isNot(AsmToken::EndOfStatement))
3362 return TokError("unexpected token in '.purgem' directive");
3363
3364 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3365 if (I == getParser().MacroMap.end())
3366 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3367
3368 // Undefine the macro.
3369 delete I->getValue();
3370 getParser().MacroMap.erase(I);
3371 return false;
3372}
3373
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003374bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003375 getParser().CheckForValidSection();
3376
3377 const MCExpr *Value;
3378
3379 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003380 return true;
3381
3382 if (getLexer().isNot(AsmToken::EndOfStatement))
3383 return TokError("unexpected token in directive");
3384
3385 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003386 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003387 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003388 getStreamer().EmitULEB128Value(Value);
3389
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003390 return false;
3391}
3392
Rafael Espindola761cb062012-06-03 23:57:14 +00003393Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003394 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003395
Rafael Espindola761cb062012-06-03 23:57:14 +00003396 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003397 for (;;) {
3398 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003399 if (getLexer().is(AsmToken::Eof)) {
3400 Error(DirectiveLoc, "no matching '.endr' in definition");
3401 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003402 }
3403
Rafael Espindola761cb062012-06-03 23:57:14 +00003404 if (Lexer.is(AsmToken::Identifier) &&
3405 (getTok().getIdentifier() == ".rept")) {
3406 ++NestLevel;
3407 }
3408
3409 // Otherwise, check whether we have reached the .endr.
3410 if (Lexer.is(AsmToken::Identifier) &&
3411 getTok().getIdentifier() == ".endr") {
3412 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003413 EndToken = getTok();
3414 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003415 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3416 TokError("unexpected token in '.endr' directive");
3417 return 0;
3418 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003419 break;
3420 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003421 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003422 }
3423
Rafael Espindola761cb062012-06-03 23:57:14 +00003424 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003425 EatToEndOfStatement();
3426 }
3427
3428 const char *BodyStart = StartToken.getLoc().getPointer();
3429 const char *BodyEnd = EndToken.getLoc().getPointer();
3430 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3431
Rafael Espindola761cb062012-06-03 23:57:14 +00003432 // We Are Anonymous.
3433 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003434 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003435 return new Macro(Name, Body, Parameters);
3436}
3437
3438void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3439 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003440 OS << ".endr\n";
3441
3442 MemoryBuffer *Instantiation =
3443 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3444
Rafael Espindola761cb062012-06-03 23:57:14 +00003445 // Create the macro instantiation object and add to the current macro
3446 // instantiation stack.
3447 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3448 getTok().getLoc(),
3449 Instantiation);
3450 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003451
Rafael Espindola761cb062012-06-03 23:57:14 +00003452 // Jump to the macro instantiation and prime the lexer.
3453 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3454 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3455 Lex();
3456}
3457
3458bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3459 int64_t Count;
3460 if (ParseAbsoluteExpression(Count))
3461 return TokError("unexpected token in '.rept' directive");
3462
3463 if (Count < 0)
3464 return TokError("Count is negative");
3465
3466 if (Lexer.isNot(AsmToken::EndOfStatement))
3467 return TokError("unexpected token in '.rept' directive");
3468
3469 // Eat the end of statement.
3470 Lex();
3471
3472 // Lex the rept definition.
3473 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3474 if (!M)
3475 return true;
3476
3477 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3478 // to hold the macro body with substitutions.
3479 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003480 MacroParameters Parameters;
3481 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003482 raw_svector_ostream OS(Buf);
3483 while (Count--) {
3484 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3485 return true;
3486 }
3487 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003488
3489 return false;
3490}
3491
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003492/// ParseDirectiveIrp
3493/// ::= .irp symbol,values
3494bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003495 MacroParameters Parameters;
3496 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003497
Preston Gurd6c9176a2012-09-19 20:29:04 +00003498 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003499 return TokError("expected identifier in '.irp' directive");
3500
3501 Parameters.push_back(Parameter);
3502
3503 if (Lexer.isNot(AsmToken::Comma))
3504 return TokError("expected comma in '.irp' directive");
3505
3506 Lex();
3507
Rafael Espindola8a403d32012-08-08 14:51:03 +00003508 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003509 if (ParseMacroArguments(0, A))
3510 return true;
3511
3512 // Eat the end of statement.
3513 Lex();
3514
3515 // Lex the irp definition.
3516 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3517 if (!M)
3518 return true;
3519
3520 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3521 // to hold the macro body with substitutions.
3522 SmallString<256> Buf;
3523 raw_svector_ostream OS(Buf);
3524
Rafael Espindola7996d042012-08-21 16:06:48 +00003525 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3526 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003527 Args.push_back(*i);
3528
3529 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3530 return true;
3531 }
3532
3533 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3534
3535 return false;
3536}
3537
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003538/// ParseDirectiveIrpc
3539/// ::= .irpc symbol,values
3540bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003541 MacroParameters Parameters;
3542 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003543
Preston Gurd6c9176a2012-09-19 20:29:04 +00003544 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003545 return TokError("expected identifier in '.irpc' directive");
3546
3547 Parameters.push_back(Parameter);
3548
3549 if (Lexer.isNot(AsmToken::Comma))
3550 return TokError("expected comma in '.irpc' directive");
3551
3552 Lex();
3553
Rafael Espindola8a403d32012-08-08 14:51:03 +00003554 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003555 if (ParseMacroArguments(0, A))
3556 return true;
3557
3558 if (A.size() != 1 || A.front().size() != 1)
3559 return TokError("unexpected token in '.irpc' directive");
3560
3561 // Eat the end of statement.
3562 Lex();
3563
3564 // Lex the irpc definition.
3565 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3566 if (!M)
3567 return true;
3568
3569 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3570 // to hold the macro body with substitutions.
3571 SmallString<256> Buf;
3572 raw_svector_ostream OS(Buf);
3573
3574 StringRef Values = A.front().front().getString();
3575 std::size_t I, End = Values.size();
3576 for (I = 0; I < End; ++I) {
3577 MacroArgument Arg;
3578 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3579
Rafael Espindola8a403d32012-08-08 14:51:03 +00003580 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003581 Args.push_back(Arg);
3582
3583 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3584 return true;
3585 }
3586
3587 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3588
3589 return false;
3590}
3591
Rafael Espindola761cb062012-06-03 23:57:14 +00003592bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3593 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003594 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003595
3596 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003597 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003598 assert(getLexer().is(AsmToken::EndOfStatement));
3599
Rafael Espindola761cb062012-06-03 23:57:14 +00003600 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003601 return false;
3602}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003603
Eli Friedman2128aae2012-10-22 23:58:19 +00003604bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3605 const MCExpr *Value;
3606 SMLoc ExprLoc = getLexer().getLoc();
3607 if (ParseExpression(Value))
3608 return true;
3609 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3610 if (!MCE)
3611 return Error(ExprLoc, "unexpected expression in _emit");
3612 uint64_t IntValue = MCE->getValue();
3613 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3614 return Error(ExprLoc, "literal value out of range for directive");
3615
3616 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3617 return false;
3618}
3619
Chad Rosierb1f8c132012-10-18 15:49:34 +00003620bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3621 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003622 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003623 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003624 SmallVectorImpl<std::string> &Clobbers,
3625 const MCInstrInfo *MII,
3626 const MCInstPrinter *IP,
3627 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003628 SmallVector<void *, 4> InputDecls;
3629 SmallVector<void *, 4> OutputDecls;
3630 SmallVector<bool, 4> InputDeclsOffsetOf;
3631 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003632 SmallVector<std::string, 4> InputConstraints;
3633 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003634 std::set<std::string> ClobberRegs;
3635
Chad Rosier4e472d22012-10-20 01:02:45 +00003636 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003637
3638 // Prime the lexer.
3639 Lex();
3640
3641 // While we have input, parse each statement.
3642 unsigned InputIdx = 0;
3643 unsigned OutputIdx = 0;
3644 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003645 ParseStatementInfo Info(&AsmStrRewrites);
3646 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003647 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003648
Eli Friedman2128aae2012-10-22 23:58:19 +00003649 if (Info.Opcode != ~0U) {
3650 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003651
3652 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003653 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3654 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003655
3656 // Immediate.
3657 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003658 if (Operand->needAsmRewrite())
3659 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3660 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003661 continue;
3662 }
3663
3664 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003665 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003666 unsigned NumDefs = Desc.getNumDefs();
3667 // Clobber.
3668 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3669 std::string Reg;
3670 raw_string_ostream OS(Reg);
3671 IP->printRegName(OS, Operand->getReg());
3672 ClobberRegs.insert(StringRef(OS.str()));
3673 }
3674 continue;
3675 }
3676
3677 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003678 unsigned Size;
3679 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3680 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003681 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003682 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003683 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003684 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003685 Operand->getStartLoc(),
3686 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003687 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003688 if (isOutput) {
3689 std::string Constraint = "=";
3690 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003691 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003692 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003693 Constraint += Operand->getConstraint().str();
3694 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003695 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003696 Operand->getStartLoc(),
3697 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003698 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003699 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003700 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003701 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003702 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003703 Operand->getStartLoc(),
3704 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003705 }
3706 }
3707 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003708 }
3709 }
3710
3711 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003712 NumOutputs = OutputDecls.size();
3713 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003714
3715 // Set the unique clobbers.
3716 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3717 E = ClobberRegs.end(); I != E; ++I)
3718 Clobbers.push_back(*I);
3719
3720 // Merge the various outputs and inputs. Output are expected first.
3721 if (NumOutputs || NumInputs) {
3722 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003723 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003724 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003725 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3726 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003727 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003728 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3729 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003730 }
3731 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003732 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3733 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003734 }
3735 }
3736
3737 // Build the IR assembly string.
3738 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003739 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003740 raw_string_ostream OS(AsmStringIR);
3741 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003742 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003743 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3744 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003745
Chad Rosier4e472d22012-10-20 01:02:45 +00003746 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003747
3748 // Emit everything up to the immediate/expression. If the previous rewrite
3749 // was a size directive, then this has already been done.
3750 if (PrevKind != AOK_SizeDirective)
3751 OS << StringRef(Start, Loc - Start);
3752 PrevKind = Kind;
3753
Chad Rosier5a719fc2012-10-23 17:43:43 +00003754 // Skip the original expression.
3755 if (Kind == AOK_Skip) {
3756 Start = Loc + (*I).Len;
3757 continue;
3758 }
3759
Chad Rosierb1f8c132012-10-18 15:49:34 +00003760 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003761 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003762 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003763 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003764 OS << Twine("$$");
3765 OS << (*I).Val;
3766 break;
3767 case AOK_ImmPrefix:
3768 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003769 break;
3770 case AOK_Input:
3771 OS << '$';
3772 OS << InputIdx++;
3773 break;
3774 case AOK_Output:
3775 OS << '$';
3776 OS << OutputIdx++;
3777 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003778 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003779 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003780 default: break;
3781 case 8: OS << "byte ptr "; break;
3782 case 16: OS << "word ptr "; break;
3783 case 32: OS << "dword ptr "; break;
3784 case 64: OS << "qword ptr "; break;
3785 case 80: OS << "xword ptr "; break;
3786 case 128: OS << "xmmword ptr "; break;
3787 case 256: OS << "ymmword ptr "; break;
3788 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003789 break;
3790 case AOK_Emit:
3791 OS << ".byte";
3792 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003793 case AOK_DotOperator:
3794 OS << (*I).Val;
3795 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003796 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003797
Chad Rosierb1f8c132012-10-18 15:49:34 +00003798 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003799 if (Kind != AOK_SizeDirective)
3800 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003801 }
3802
3803 // Emit the remainder of the asm string.
3804 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3805 if (Start != AsmEnd)
3806 OS << StringRef(Start, AsmEnd - Start);
3807
3808 AsmString = OS.str();
3809 return false;
3810}
3811
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003812/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003813MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003814 MCContext &C, MCStreamer &Out,
3815 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003816 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003817}