blob: 106dd539074bec5c9081eae013d53d37df2b4bf8 [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;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000157 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158
Devang Patel0db58bf2012-01-31 18:14:05 +0000159 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
160 unsigned AssemblerDialect;
161
Preston Gurd7b6f2032012-09-19 20:36:12 +0000162 /// IsDarwin - is Darwin compatibility enabled?
163 bool IsDarwin;
164
Chad Rosier8f138d12012-10-15 17:19:13 +0000165 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000166 bool ParsingInlineAsm;
167
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000168public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000169 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000170 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000171 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000172
173 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
174
Craig Topper345d16d2012-08-29 05:48:09 +0000175 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
176 StringRef Directive,
177 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178 DirectiveMap[Directive] = std::make_pair(Object, Handler);
179 }
180
181public:
182 /// @name MCAsmParser Interface
183 /// {
184
185 virtual SourceMgr &getSourceManager() { return SrcMgr; }
186 virtual MCAsmLexer &getLexer() { return Lexer; }
187 virtual MCContext &getContext() { return Ctx; }
188 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000189 virtual unsigned getAssemblerDialect() {
190 if (AssemblerDialect == ~0U)
191 return MAI.getAssemblerDialect();
192 else
193 return AssemblerDialect;
194 }
195 virtual void setAssemblerDialect(unsigned i) {
196 AssemblerDialect = i;
197 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000198
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000199 virtual bool Warning(SMLoc L, const Twine &Msg,
200 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
201 virtual bool Error(SMLoc L, const Twine &Msg,
202 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000203
Craig Topper345d16d2012-08-29 05:48:09 +0000204 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000205
Chad Rosier84125ca2012-10-13 00:26:04 +0000206 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000207 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000208
209 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
210 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000211 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000213 SmallVectorImpl<std::string> &Clobbers,
214 const MCInstrInfo *MII,
215 const MCInstPrinter *IP,
216 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000217
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000218 bool ParseExpression(const MCExpr *&Res);
219 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
220 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
221 virtual bool ParseAbsoluteExpression(int64_t &Res);
222
223 /// }
224
225private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000226 void CheckForValidSection();
227
Eli Friedman2128aae2012-10-22 23:58:19 +0000228 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000229 void EatToEndOfLine();
230 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000231
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000232 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000233 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000234 const MacroParameters &Parameters,
235 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000236 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000237 void HandleMacroExit();
238
239 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000240 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000241 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
242 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000243 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000244 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000245
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000246 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
247 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000248 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
249 /// This returns true on failure.
250 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000251
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000252 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000253 /// current token is not set; clients should ensure Lex() is called
254 /// subsequently.
255 void JumpToLoc(SMLoc Loc);
256
Craig Topper345d16d2012-08-29 05:48:09 +0000257 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000258
Preston Gurd7b6f2032012-09-19 20:36:12 +0000259 bool ParseMacroArgument(MacroArgument &MA,
260 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000261 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000262
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000263 /// \brief Parse up to the end of statement and a return the contents from the
264 /// current token until the end of the statement; the current token on exit
265 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000266 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000267
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000268 /// \brief Parse until the end of a statement or a comma is encountered,
269 /// return the contents from the current token up to the end or comma.
270 StringRef ParseStringToComma();
271
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000272 bool ParseAssignment(StringRef Name, bool allow_redef,
273 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000274
275 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
276 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
277 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000278 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000279
280 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000281 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000282 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000283
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000284 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000285
286 // ".ascii", ".asciiz", ".string"
287 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000288 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000289 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290 bool ParseDirectiveFill(); // ".fill"
291 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000292 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000293 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000294 bool ParseDirectiveOrg(); // ".org"
295 // ".align{,32}", ".p2align{,w,l}"
296 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
297
298 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
299 /// accepts a single symbol (which should be a label or an external).
300 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000301
302 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
303
304 bool ParseDirectiveAbort(); // ".abort"
305 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000306 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000307
308 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000309 // ".ifb" or ".ifnb", depending on ExpectBlank.
310 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000311 // ".ifc" or ".ifnc", depending on ExpectEqual.
312 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000313 // ".ifdef" or ".ifndef", depending on expect_defined
314 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
316 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
317 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
318
319 /// ParseEscapedString - Parse the current token as a string which may include
320 /// escaped characters and return the string contents.
321 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000322
323 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
324 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000325
Rafael Espindola761cb062012-06-03 23:57:14 +0000326 // Macro-like directives
327 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
328 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
329 raw_svector_ostream &OS);
330 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000331 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000332 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000333 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000334
Eli Friedman2128aae2012-10-22 23:58:19 +0000335 // "_emit"
336 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000337};
338
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000339/// \brief Generic implementations of directive handling, etc. which is shared
340/// (or the default, at least) for all assembler parser.
341class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000342 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
343 void AddDirectiveHandler(StringRef Directive) {
344 getParser().AddDirectiveHandler(this, Directive,
345 HandleDirective<GenericAsmParser, Handler>);
346 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000347public:
348 GenericAsmParser() {}
349
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000350 AsmParser &getParser() {
351 return (AsmParser&) this->MCAsmParserExtension::getParser();
352 }
353
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000354 virtual void Initialize(MCAsmParser &Parser) {
355 // Call the base implementation.
356 this->MCAsmParserExtension::Initialize(Parser);
357
358 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000363
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000364 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
366 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000367 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
368 ".cfi_startproc");
369 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
370 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000371 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
372 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000373 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
374 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000375 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
376 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
378 ".cfi_def_cfa_register");
379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
380 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000381 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
382 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000383 AddDirectiveHandler<
384 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
385 AddDirectiveHandler<
386 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000387 AddDirectiveHandler<
388 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
389 AddDirectiveHandler<
390 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000391 AddDirectiveHandler<
392 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000393 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000394 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
395 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000396 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000397 AddDirectiveHandler<
398 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000399 AddDirectiveHandler<
400 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000401 AddDirectiveHandler<
402 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000403
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000404 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
406 ".macros_on");
407 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
408 ".macros_off");
409 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
411 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000412 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000413
414 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
415 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000416 }
417
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000418 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
419
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000420 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
421 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000423 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000424 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000425 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
426 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000427 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000428 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000429 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000430 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
431 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000432 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000433 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000434 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
435 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000436 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000437 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000438 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000439 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000440 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000441 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000442
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000443 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000444 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
445 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000446 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000447
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000448 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000449};
450
451}
452
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000453namespace llvm {
454
455extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000456extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000457extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000458
459}
460
Chris Lattneraaec2052010-01-19 19:46:13 +0000461enum { DEFAULT_ADDRSPACE = 0 };
462
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000463AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000464 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000465 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000466 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000467 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000468 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000469 // Save the old handler.
470 SavedDiagHandler = SrcMgr.getDiagHandler();
471 SavedDiagContext = SrcMgr.getDiagContext();
472 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000473 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000474 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000475
476 // Initialize the generic parser.
477 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000478
479 // Initialize the platform / file format parser.
480 //
481 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
482 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000483 if (_MAI.hasMicrosoftFastStdCallMangling()) {
484 PlatformParser = createCOFFAsmParser();
485 PlatformParser->Initialize(*this);
486 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000487 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000488 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000489 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000490 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000491 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000492 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000493 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000494}
495
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000496AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000497 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
498
499 // Destroy any macros.
500 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
501 ie = MacroMap.end(); it != ie; ++it)
502 delete it->getValue();
503
Daniel Dunbare4749702010-07-12 18:12:02 +0000504 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000505 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000506}
507
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000508void AsmParser::PrintMacroInstantiations() {
509 // Print the active macro instantiation stack.
510 for (std::vector<MacroInstantiation*>::const_reverse_iterator
511 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000512 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
513 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000514}
515
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000516bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000517 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000518 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000519 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000520 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000521 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000522}
523
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000524bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000525 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000526 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000527 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000528 return true;
529}
530
Sean Callananfd0b0282010-01-21 00:19:58 +0000531bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000532 std::string IncludedFile;
533 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000534 if (NewBuf == -1)
535 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000536
Sean Callananfd0b0282010-01-21 00:19:58 +0000537 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000538
Sean Callananfd0b0282010-01-21 00:19:58 +0000539 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541 return false;
542}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000543
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000544/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000545/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000546/// returns true on failure.
547bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
548 std::string IncludedFile;
549 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
550 if (NewBuf == -1)
551 return true;
552
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000553 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000554 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
555 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000556 return false;
557}
558
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000559void AsmParser::JumpToLoc(SMLoc Loc) {
560 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
561 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
562}
563
Sean Callananfd0b0282010-01-21 00:19:58 +0000564const AsmToken &AsmParser::Lex() {
565 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000566
Sean Callananfd0b0282010-01-21 00:19:58 +0000567 if (tok->is(AsmToken::Eof)) {
568 // If this is the end of an included file, pop the parent file off the
569 // include stack.
570 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
571 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000572 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000573 tok = &Lexer.Lex();
574 }
575 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000576
Sean Callananfd0b0282010-01-21 00:19:58 +0000577 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000578 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000581}
582
Chris Lattner79180e22010-04-05 23:15:42 +0000583bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000584 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000585 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000586 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000587
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000588 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000589 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000590
591 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000592 AsmCond StartingCondState = TheCondState;
593
Kevin Enderby613b7572011-11-01 22:27:22 +0000594 // If we are generating dwarf for assembly source files save the initial text
595 // section and generate a .file directive.
596 if (getContext().getGenDwarfForAssembly()) {
597 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000598 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
599 getStreamer().EmitLabel(SectionStartSym);
600 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000601 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
602 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
603 }
604
Chris Lattnerb717fb02009-07-02 21:53:43 +0000605 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000606 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000607 ParseStatementInfo Info;
608 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000609
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000610 // We had an error, validate that one was emitted and recover by skipping to
611 // the next line.
612 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000613 EatToEndOfStatement();
614 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000615
616 if (TheCondState.TheCond != StartingCondState.TheCond ||
617 TheCondState.Ignore != StartingCondState.Ignore)
618 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000619
620 // Check to see there are no empty DwarfFile slots.
621 const std::vector<MCDwarfFile *> &MCDwarfFiles =
622 getContext().getMCDwarfFiles();
623 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000624 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000625 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000626 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000627
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000628 // Check to see that all assembler local symbols were actually defined.
629 // Targets that don't do subsections via symbols may not want this, though,
630 // so conservatively exclude them. Only do this if we're finalizing, though,
631 // as otherwise we won't necessarilly have seen everything yet.
632 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
633 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
634 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
635 e = Symbols.end();
636 i != e; ++i) {
637 MCSymbol *Sym = i->getValue();
638 // Variable symbols may not be marked as defined, so check those
639 // explicitly. If we know it's a variable, we have a definition for
640 // the purposes of this check.
641 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
642 // FIXME: We would really like to refer back to where the symbol was
643 // first referenced for a source location. We need to add something
644 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000645 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
646 "assembler local symbol '" + Sym->getName() +
647 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000648 }
649 }
650
651
Chris Lattner79180e22010-04-05 23:15:42 +0000652 // Finalize the output stream if there are no errors and if the client wants
653 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000654 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000655 Out.Finish();
656
Chris Lattnerb717fb02009-07-02 21:53:43 +0000657 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000658}
659
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000660void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000661 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000662 TokError("expected section directive before assembly directive");
663 Out.SwitchSection(Ctx.getMachOSection(
664 "__TEXT", "__text",
665 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
666 0, SectionKind::getText()));
667 }
668}
669
Chris Lattner2cf5f142009-06-22 01:29:09 +0000670/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
671void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000672 while (Lexer.isNot(AsmToken::EndOfStatement) &&
673 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000674 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000675
Chris Lattner2cf5f142009-06-22 01:29:09 +0000676 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000677 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000678 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000679}
680
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000681StringRef AsmParser::ParseStringToEndOfStatement() {
682 const char *Start = getTok().getLoc().getPointer();
683
684 while (Lexer.isNot(AsmToken::EndOfStatement) &&
685 Lexer.isNot(AsmToken::Eof))
686 Lex();
687
688 const char *End = getTok().getLoc().getPointer();
689 return StringRef(Start, End - Start);
690}
Chris Lattnerc4193832009-06-22 05:51:26 +0000691
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000692StringRef AsmParser::ParseStringToComma() {
693 const char *Start = getTok().getLoc().getPointer();
694
695 while (Lexer.isNot(AsmToken::EndOfStatement) &&
696 Lexer.isNot(AsmToken::Comma) &&
697 Lexer.isNot(AsmToken::Eof))
698 Lex();
699
700 const char *End = getTok().getLoc().getPointer();
701 return StringRef(Start, End - Start);
702}
703
Chris Lattner74ec1a32009-06-22 06:32:03 +0000704/// ParseParenExpr - Parse a paren expression and return it.
705/// NOTE: This assumes the leading '(' has already been consumed.
706///
707/// parenexpr ::= expr)
708///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000709bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000711 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000712 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000713 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000714 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000715 return false;
716}
Chris Lattnerc4193832009-06-22 05:51:26 +0000717
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000718/// ParseBracketExpr - Parse a bracket expression and return it.
719/// NOTE: This assumes the leading '[' has already been consumed.
720///
721/// bracketexpr ::= expr]
722///
723bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
724 if (ParseExpression(Res)) return true;
725 if (Lexer.isNot(AsmToken::RBrac))
726 return TokError("expected ']' in brackets expression");
727 EndLoc = Lexer.getLoc();
728 Lex();
729 return false;
730}
731
Chris Lattner74ec1a32009-06-22 06:32:03 +0000732/// ParsePrimaryExpr - Parse a primary expression and return it.
733/// primaryexpr ::= (parenexpr
734/// primaryexpr ::= symbol
735/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000736/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000738bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000739 switch (Lexer.getKind()) {
740 default:
741 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000742 // If we have an error assume that we've already handled it.
743 case AsmToken::Error:
744 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000745 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000746 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000747 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000748 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000749 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000750 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000751 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000752 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000753 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000754 EndLoc = Lexer.getLoc();
755
756 StringRef Identifier;
757 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000758 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000759
Daniel Dunbarfffff912009-10-16 01:34:54 +0000760 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000761 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000762 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000763
764 // Lookup the symbol variant if used.
765 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000766 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000767 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000768 if (Variant == MCSymbolRefExpr::VK_Invalid) {
769 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000770 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000771 }
772 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000773
Daniel Dunbarfffff912009-10-16 01:34:54 +0000774 // If this is an absolute variable reference, substitute it now to preserve
775 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000776 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000777 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000778 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000779
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000780 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000781 return false;
782 }
783
784 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000785 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000786 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000787 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000788 case AsmToken::Integer: {
789 SMLoc Loc = getTok().getLoc();
790 int64_t IntVal = getTok().getIntVal();
791 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000792 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000793 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000794 // Look for 'b' or 'f' following an Integer as a directional label
795 if (Lexer.getKind() == AsmToken::Identifier) {
796 StringRef IDVal = getTok().getString();
797 if (IDVal == "f" || IDVal == "b"){
798 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
799 IDVal == "f" ? 1 : 0);
800 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
801 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000802 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000803 return Error(Loc, "invalid reference to undefined symbol");
804 EndLoc = Lexer.getLoc();
805 Lex(); // Eat identifier.
806 }
807 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000808 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000809 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000810 case AsmToken::Real: {
811 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000812 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000813 Res = MCConstantExpr::Create(IntVal, getContext());
814 Lex(); // Eat token.
815 return false;
816 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000817 case AsmToken::Dot: {
818 // This is a '.' reference, which references the current PC. Emit a
819 // temporary label to the streamer and refer to it.
820 MCSymbol *Sym = Ctx.CreateTempSymbol();
821 Out.EmitLabel(Sym);
822 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
823 EndLoc = Lexer.getLoc();
824 Lex(); // Eat identifier.
825 return false;
826 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000827 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000828 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000829 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000830 case AsmToken::LBrac:
831 if (!PlatformParser->HasBracketExpressions())
832 return TokError("brackets expression not supported on this target");
833 Lex(); // Eat the '['.
834 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000835 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000836 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000837 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000838 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000839 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000840 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000841 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000842 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000843 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000844 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000845 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000846 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000847 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000848 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000849 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000851 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000853 }
854}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000855
Chris Lattnerb4307b32010-01-15 19:28:38 +0000856bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000857 SMLoc EndLoc;
858 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000859}
860
Daniel Dunbarcceba832010-09-17 02:47:07 +0000861const MCExpr *
862AsmParser::ApplyModifierToExpr(const MCExpr *E,
863 MCSymbolRefExpr::VariantKind Variant) {
864 // Recurse over the given expression, rebuilding it to apply the given variant
865 // if there is exactly one symbol.
866 switch (E->getKind()) {
867 case MCExpr::Target:
868 case MCExpr::Constant:
869 return 0;
870
871 case MCExpr::SymbolRef: {
872 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
873
874 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
875 TokError("invalid variant on expression '" +
876 getTok().getIdentifier() + "' (already modified)");
877 return E;
878 }
879
880 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
881 }
882
883 case MCExpr::Unary: {
884 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
885 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
886 if (!Sub)
887 return 0;
888 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
889 }
890
891 case MCExpr::Binary: {
892 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
893 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
894 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
895
896 if (!LHS && !RHS)
897 return 0;
898
899 if (!LHS) LHS = BE->getLHS();
900 if (!RHS) RHS = BE->getRHS();
901
902 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
903 }
904 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000905
Craig Topper85814382012-02-07 05:05:23 +0000906 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000907}
908
Chris Lattner74ec1a32009-06-22 06:32:03 +0000909/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000910///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000911/// expr ::= expr &&,|| expr -> lowest.
912/// expr ::= expr |,^,&,! expr
913/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
914/// expr ::= expr <<,>> expr
915/// expr ::= expr +,- expr
916/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000917/// expr ::= primaryexpr
918///
Chris Lattner54482b42010-01-15 19:39:23 +0000919bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000920 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000921 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000922 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
923 return true;
924
Daniel Dunbarcceba832010-09-17 02:47:07 +0000925 // As a special case, we support 'a op b @ modifier' by rewriting the
926 // expression to include the modifier. This is inefficient, but in general we
927 // expect users to use 'a@modifier op b'.
928 if (Lexer.getKind() == AsmToken::At) {
929 Lex();
930
931 if (Lexer.isNot(AsmToken::Identifier))
932 return TokError("unexpected symbol modifier following '@'");
933
934 MCSymbolRefExpr::VariantKind Variant =
935 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
936 if (Variant == MCSymbolRefExpr::VK_Invalid)
937 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
938
939 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
940 if (!ModifiedRes) {
941 return TokError("invalid modifier '" + getTok().getIdentifier() +
942 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000943 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000944
Daniel Dunbarcceba832010-09-17 02:47:07 +0000945 Res = ModifiedRes;
946 Lex();
947 }
948
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000949 // Try to constant fold it up front, if possible.
950 int64_t Value;
951 if (Res->EvaluateAsAbsolute(Value))
952 Res = MCConstantExpr::Create(Value, getContext());
953
954 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000955}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000956
Chris Lattnerb4307b32010-01-15 19:28:38 +0000957bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000958 Res = 0;
959 return ParseParenExpr(Res, EndLoc) ||
960 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000961}
962
Daniel Dunbar475839e2009-06-29 20:37:27 +0000963bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000964 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000965
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000966 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000967 if (ParseExpression(Expr))
968 return true;
969
Daniel Dunbare00b0112009-10-16 01:57:52 +0000970 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000971 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000972
973 return false;
974}
975
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000976static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000977 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000978 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000979 default:
980 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000981
Jim Grosbachfbe16812011-08-20 16:24:13 +0000982 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000983 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000984 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000985 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000986 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000987 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000988 return 1;
989
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000990
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000991 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000992 //
993 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000994 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000995 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000996 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000997 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000998 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000999 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001000 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001001 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001002 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001003
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001004 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001005 case AsmToken::EqualEqual:
1006 Kind = MCBinaryExpr::EQ;
1007 return 3;
1008 case AsmToken::ExclaimEqual:
1009 case AsmToken::LessGreater:
1010 Kind = MCBinaryExpr::NE;
1011 return 3;
1012 case AsmToken::Less:
1013 Kind = MCBinaryExpr::LT;
1014 return 3;
1015 case AsmToken::LessEqual:
1016 Kind = MCBinaryExpr::LTE;
1017 return 3;
1018 case AsmToken::Greater:
1019 Kind = MCBinaryExpr::GT;
1020 return 3;
1021 case AsmToken::GreaterEqual:
1022 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001023 return 3;
1024
Jim Grosbachfbe16812011-08-20 16:24:13 +00001025 // Intermediate Precedence: <<, >>
1026 case AsmToken::LessLess:
1027 Kind = MCBinaryExpr::Shl;
1028 return 4;
1029 case AsmToken::GreaterGreater:
1030 Kind = MCBinaryExpr::Shr;
1031 return 4;
1032
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001033 // High Intermediate Precedence: +, -
1034 case AsmToken::Plus:
1035 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001036 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001037 case AsmToken::Minus:
1038 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001039 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001040
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001042 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001043 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001044 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001045 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001046 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001047 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001048 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001049 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001050 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001051 }
1052}
1053
1054
1055/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1056/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001057bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1058 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001059 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001060 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001061 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001062
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001063 // If the next token is lower precedence than we are allowed to eat, return
1064 // successfully with what we ate already.
1065 if (TokPrec < Precedence)
1066 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001067
Sean Callanan79ed1a82010-01-19 20:22:31 +00001068 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001069
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001070 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001071 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001072 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001073
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 // If BinOp binds less tightly with RHS than the operator after RHS, let
1075 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001076 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001077 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001078 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001079 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001080 }
1081
Daniel Dunbar475839e2009-06-29 20:37:27 +00001082 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001083 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 }
1085}
1086
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001087/// ParseStatement:
1088/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001089/// ::= Label* Directive ...Operands... EndOfStatement
1090/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001091bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001092 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001093 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001094 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001095 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001096 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001097
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001098 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001099 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001100 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001101 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001102 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001103 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001104 if (Lexer.is(AsmToken::Hash))
1105 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001106
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001107 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001108 if (Lexer.is(AsmToken::Integer)) {
1109 LocalLabelVal = getTok().getIntVal();
1110 if (LocalLabelVal < 0) {
1111 if (!TheCondState.Ignore)
1112 return TokError("unexpected token at start of statement");
1113 IDVal = "";
1114 }
1115 else {
1116 IDVal = getTok().getString();
1117 Lex(); // Consume the integer token to be used as an identifier token.
1118 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001119 if (!TheCondState.Ignore)
1120 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001121 }
1122 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001123
1124 } else if (Lexer.is(AsmToken::Dot)) {
1125 // Treat '.' as a valid identifier in this context.
1126 Lex();
1127 IDVal = ".";
1128
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001129 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001130 if (!TheCondState.Ignore)
1131 return TokError("unexpected token at start of statement");
1132 IDVal = "";
1133 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001134
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001135
Chris Lattner7834fac2010-04-17 18:14:27 +00001136 // Handle conditional assembly here before checking for skipping. We
1137 // have to do this so that .endif isn't skipped in a ".if 0" block for
1138 // example.
1139 if (IDVal == ".if")
1140 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001141 if (IDVal == ".ifb")
1142 return ParseDirectiveIfb(IDLoc, true);
1143 if (IDVal == ".ifnb")
1144 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001145 if (IDVal == ".ifc")
1146 return ParseDirectiveIfc(IDLoc, true);
1147 if (IDVal == ".ifnc")
1148 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001149 if (IDVal == ".ifdef")
1150 return ParseDirectiveIfdef(IDLoc, true);
1151 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1152 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001153 if (IDVal == ".elseif")
1154 return ParseDirectiveElseIf(IDLoc);
1155 if (IDVal == ".else")
1156 return ParseDirectiveElse(IDLoc);
1157 if (IDVal == ".endif")
1158 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001159
Chris Lattner7834fac2010-04-17 18:14:27 +00001160 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001161 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001162 EatToEndOfStatement();
1163 return false;
1164 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001165
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001166 // FIXME: Recurse on local labels?
1167
1168 // See what kind of statement we have.
1169 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001170 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001171 CheckForValidSection();
1172
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001173 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001174 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001175
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001176 // Diagnose attempt to use '.' as a label.
1177 if (IDVal == ".")
1178 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1179
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001180 // Diagnose attempt to use a variable as a label.
1181 //
1182 // FIXME: Diagnostics. Note the location of the definition as a label.
1183 // FIXME: This doesn't diagnose assignment to a symbol which has been
1184 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001185 MCSymbol *Sym;
1186 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001187 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001188 else
1189 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001190 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001191 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001192
Daniel Dunbar959fd882009-08-26 22:13:22 +00001193 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001194 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001195
Kevin Enderby94c2e852011-12-09 18:09:40 +00001196 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001197 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001198 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001199 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1200 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001201
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001202 // Consume any end of statement token, if present, to avoid spurious
1203 // AddBlankLine calls().
1204 if (Lexer.is(AsmToken::EndOfStatement)) {
1205 Lex();
1206 if (Lexer.is(AsmToken::Eof))
1207 return false;
1208 }
1209
Eli Friedman2128aae2012-10-22 23:58:19 +00001210 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001211 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001212
Daniel Dunbar3f872332009-07-28 16:08:33 +00001213 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001214 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001215 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001216
Nico Weber4c4c7322011-01-28 03:04:41 +00001217 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001218
1219 default: // Normal instruction or directive.
1220 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001221 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001222
1223 // If macros are enabled, check to see if this is a macro instantiation.
1224 if (MacrosEnabled)
1225 if (const Macro *M = MacroMap.lookup(IDVal))
1226 return HandleMacroEntry(IDVal, IDLoc, M);
1227
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001228 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001229 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001230
1231 // Target hook for parsing target specific directives.
1232 if (!getTargetParser().ParseDirective(ID))
1233 return false;
1234
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001235 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001236 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001237 return ParseDirectiveSet(IDVal, true);
1238 if (IDVal == ".equiv")
1239 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001240
Daniel Dunbara0d14262009-06-24 23:30:00 +00001241 // Data directives
1242
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001243 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001244 return ParseDirectiveAscii(IDVal, false);
1245 if (IDVal == ".asciz" || IDVal == ".string")
1246 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001247
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001248 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001249 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001250 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001251 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001252 if (IDVal == ".value")
1253 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001254 if (IDVal == ".2byte")
1255 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001257 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001258 if (IDVal == ".int")
1259 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001260 if (IDVal == ".4byte")
1261 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001262 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001263 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001264 if (IDVal == ".8byte")
1265 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001266 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001267 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1268 if (IDVal == ".double")
1269 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001270
Eli Friedman5d68ec22010-07-19 04:17:25 +00001271 if (IDVal == ".align") {
1272 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1273 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1274 }
1275 if (IDVal == ".align32") {
1276 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1277 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1278 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001279 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001280 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001281 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001282 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001283 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001284 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001285 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001286 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001287 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001288 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001290 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1291
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001292 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001293 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001294
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001295 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001296 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001297 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001298 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001299 if (IDVal == ".zero")
1300 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001301
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001302 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001303
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001304 if (IDVal == ".extern") {
1305 EatToEndOfStatement(); // .extern is the default, ignore it.
1306 return false;
1307 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001308 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001309 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001310 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001311 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001312 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001313 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001314 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001315 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001316 if (IDVal == ".symbol_resolver")
1317 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001318 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001319 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001320 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001321 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001322 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001323 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001324 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001325 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001326 if (IDVal == ".weak_def_can_be_hidden")
1327 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001328
Hans Wennborg5cc64912011-06-18 13:51:54 +00001329 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001330 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001331 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001332 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001333
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001334 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001335 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001336 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001337 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001338 if (IDVal == ".incbin")
1339 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001340
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001341 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001342 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001343
Rafael Espindola761cb062012-06-03 23:57:14 +00001344 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001345 if (IDVal == ".rept")
1346 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001347 if (IDVal == ".irp")
1348 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001349 if (IDVal == ".irpc")
1350 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001351 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001352 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001353
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001354 // Look up the handler in the handler table.
1355 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1356 DirectiveMap.lookup(IDVal);
1357 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001358 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001359
Kevin Enderby9c656452009-09-10 20:51:44 +00001360
Jim Grosbach686c0182012-05-01 18:38:27 +00001361 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001362 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001363
Eli Friedman2128aae2012-10-22 23:58:19 +00001364 // _emit
1365 if (ParsingInlineAsm && IDVal == "_emit")
1366 return ParseDirectiveEmit(IDLoc, Info);
1367
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001368 CheckForValidSection();
1369
Chris Lattnera7f13542010-05-19 23:34:33 +00001370 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001371 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001372 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001373 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001374
Chad Rosier6a020a72012-10-25 20:41:34 +00001375 ParseInstructionInfo IInfo(Info.AsmRewrites);
1376 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1377 IDLoc,Info.ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001378
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001379 // Dump the parsed representation, if requested.
1380 if (getShowParsedOperands()) {
1381 SmallString<256> Str;
1382 raw_svector_ostream OS(Str);
1383 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001384 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001385 if (i != 0)
1386 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001387 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001388 }
1389 OS << "]";
1390
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001391 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001392 }
1393
Kevin Enderby613b7572011-11-01 22:27:22 +00001394 // If we are generating dwarf for assembly source files and the current
1395 // section is the initial text section then generate a .loc directive for
1396 // the instruction.
1397 if (!HadError && getContext().getGenDwarfForAssembly() &&
1398 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001399
1400 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1401
1402 // If we previously parsed a cpp hash file line comment then make sure the
1403 // current Dwarf File is for the CppHashFilename if not then emit the
1404 // Dwarf File table for it and adjust the line number for the .loc.
1405 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1406 getContext().getMCDwarfFiles();
1407 if (CppHashFilename.size() != 0) {
1408 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1409 CppHashFilename)
1410 getStreamer().EmitDwarfFileDirective(
1411 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1412
Kevin Enderby32c1a822012-11-05 21:55:41 +00001413 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001414 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1415 }
1416
Kevin Enderby613b7572011-11-01 22:27:22 +00001417 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001418 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001419 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001420 StringRef());
1421 }
1422
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001423 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001424 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001425 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001426 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1427 Info.ParsedOperands,
1428 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001429 ParsingInlineAsm);
1430 }
Chris Lattner98986712010-01-14 22:21:20 +00001431
Chris Lattnercbf8a982010-09-11 16:18:25 +00001432 // Don't skip the rest of the line, the instruction parser is responsible for
1433 // that.
1434 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001435}
Chris Lattner9a023f72009-06-24 04:43:34 +00001436
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001437/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1438/// since they may not be able to be tokenized to get to the end of line token.
1439void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001440 if (!Lexer.is(AsmToken::EndOfStatement))
1441 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001442 // Eat EOL.
1443 Lex();
1444}
1445
1446/// ParseCppHashLineFilenameComment as this:
1447/// ::= # number "filename"
1448/// or just as a full line comment if it doesn't have a number and a string.
1449bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1450 Lex(); // Eat the hash token.
1451
1452 if (getLexer().isNot(AsmToken::Integer)) {
1453 // Consume the line since in cases it is not a well-formed line directive,
1454 // as if were simply a full line comment.
1455 EatToEndOfLine();
1456 return false;
1457 }
1458
1459 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001460 Lex();
1461
1462 if (getLexer().isNot(AsmToken::String)) {
1463 EatToEndOfLine();
1464 return false;
1465 }
1466
1467 StringRef Filename = getTok().getString();
1468 // Get rid of the enclosing quotes.
1469 Filename = Filename.substr(1, Filename.size()-2);
1470
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001471 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1472 CppHashLoc = L;
1473 CppHashFilename = Filename;
1474 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001475 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001476
1477 // Ignore any trailing characters, they're just comment.
1478 EatToEndOfLine();
1479 return false;
1480}
1481
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001482/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001483/// for the Filename and LineNo if any in the diagnostic.
1484void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1485 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1486 raw_ostream &OS = errs();
1487
1488 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1489 const SMLoc &DiagLoc = Diag.getLoc();
1490 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1491 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1492
1493 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1494 // before printing the message.
1495 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001496 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001497 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1498 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1499 }
1500
1501 // If we have not parsed a cpp hash line filename comment or the source
1502 // manager changed or buffer changed (like in a nested include) then just
1503 // print the normal diagnostic using its Filename and LineNo.
1504 if (!Parser->CppHashLineNumber ||
1505 &DiagSrcMgr != &Parser->SrcMgr ||
1506 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001507 if (Parser->SavedDiagHandler)
1508 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1509 else
1510 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001511 return;
1512 }
1513
1514 // Use the CppHashFilename and calculate a line number based on the
1515 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1516 // the diagnostic.
1517 const std::string Filename = Parser->CppHashFilename;
1518
1519 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1520 int CppHashLocLineNo =
1521 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1522 int LineNo = Parser->CppHashLineNumber - 1 +
1523 (DiagLocLineNo - CppHashLocLineNo);
1524
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001525 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1526 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001527 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001528 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001529
Benjamin Kramer04a04262011-10-16 10:48:29 +00001530 if (Parser->SavedDiagHandler)
1531 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1532 else
1533 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001534}
1535
Rafael Espindola799aacf2012-08-21 18:29:30 +00001536// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1537// difference being that that function accepts '@' as part of identifiers and
1538// we can't do that. AsmLexer.cpp should probably be changed to handle
1539// '@' as a special case when needed.
1540static bool isIdentifierChar(char c) {
1541 return isalnum(c) || c == '_' || c == '$' || c == '.';
1542}
1543
Rafael Espindola761cb062012-06-03 23:57:14 +00001544bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001545 const MacroParameters &Parameters,
1546 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001547 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001548 unsigned NParameters = Parameters.size();
1549 if (NParameters != 0 && NParameters != A.size())
1550 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001551
Preston Gurd7b6f2032012-09-19 20:36:12 +00001552 // A macro without parameters is handled differently on Darwin:
1553 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001554 while (!Body.empty()) {
1555 // Scan for the next substitution.
1556 std::size_t End = Body.size(), Pos = 0;
1557 for (; Pos != End; ++Pos) {
1558 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001559 if (!NParameters) {
1560 // This macro has no parameters, look for $0, $1, etc.
1561 if (Body[Pos] != '$' || Pos + 1 == End)
1562 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001563
Rafael Espindola65366442011-06-05 02:43:45 +00001564 char Next = Body[Pos + 1];
1565 if (Next == '$' || Next == 'n' || isdigit(Next))
1566 break;
1567 } else {
1568 // This macro has parameters, look for \foo, \bar, etc.
1569 if (Body[Pos] == '\\' && Pos + 1 != End)
1570 break;
1571 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001572 }
1573
1574 // Add the prefix.
1575 OS << Body.slice(0, Pos);
1576
1577 // Check if we reached the end.
1578 if (Pos == End)
1579 break;
1580
Rafael Espindola65366442011-06-05 02:43:45 +00001581 if (!NParameters) {
1582 switch (Body[Pos+1]) {
1583 // $$ => $
1584 case '$':
1585 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001586 break;
1587
Rafael Espindola65366442011-06-05 02:43:45 +00001588 // $n => number of arguments
1589 case 'n':
1590 OS << A.size();
1591 break;
1592
1593 // $[0-9] => argument
1594 default: {
1595 // Missing arguments are ignored.
1596 unsigned Index = Body[Pos+1] - '0';
1597 if (Index >= A.size())
1598 break;
1599
1600 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001601 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001602 ie = A[Index].end(); it != ie; ++it)
1603 OS << it->getString();
1604 break;
1605 }
1606 }
1607 Pos += 2;
1608 } else {
1609 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001610 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001611 ++I;
1612
1613 const char *Begin = Body.data() + Pos +1;
1614 StringRef Argument(Begin, I - (Pos +1));
1615 unsigned Index = 0;
1616 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001617 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001618 break;
1619
Preston Gurd7b6f2032012-09-19 20:36:12 +00001620 if (Index == NParameters) {
1621 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1622 Pos += 3;
1623 else {
1624 OS << '\\' << Argument;
1625 Pos = I;
1626 }
1627 } else {
1628 for (MacroArgument::const_iterator it = A[Index].begin(),
1629 ie = A[Index].end(); it != ie; ++it)
1630 if (it->getKind() == AsmToken::String)
1631 OS << it->getStringContents();
1632 else
1633 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001634
Preston Gurd7b6f2032012-09-19 20:36:12 +00001635 Pos += 1 + Argument.size();
1636 }
Rafael Espindola65366442011-06-05 02:43:45 +00001637 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001638 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001639 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001640 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001641
Rafael Espindola65366442011-06-05 02:43:45 +00001642 return false;
1643}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001644
Rafael Espindola65366442011-06-05 02:43:45 +00001645MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1646 MemoryBuffer *I)
1647 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1648{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001649}
1650
Preston Gurd7b6f2032012-09-19 20:36:12 +00001651static bool IsOperator(AsmToken::TokenKind kind)
1652{
1653 switch (kind)
1654 {
1655 default:
1656 return false;
1657 case AsmToken::Plus:
1658 case AsmToken::Minus:
1659 case AsmToken::Tilde:
1660 case AsmToken::Slash:
1661 case AsmToken::Star:
1662 case AsmToken::Dot:
1663 case AsmToken::Equal:
1664 case AsmToken::EqualEqual:
1665 case AsmToken::Pipe:
1666 case AsmToken::PipePipe:
1667 case AsmToken::Caret:
1668 case AsmToken::Amp:
1669 case AsmToken::AmpAmp:
1670 case AsmToken::Exclaim:
1671 case AsmToken::ExclaimEqual:
1672 case AsmToken::Percent:
1673 case AsmToken::Less:
1674 case AsmToken::LessEqual:
1675 case AsmToken::LessLess:
1676 case AsmToken::LessGreater:
1677 case AsmToken::Greater:
1678 case AsmToken::GreaterEqual:
1679 case AsmToken::GreaterGreater:
1680 return true;
1681 }
1682}
1683
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001684/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1685/// This is used for both default macro parameter values and the
1686/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001687bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1688 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001689 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001690 unsigned AddTokens = 0;
1691
1692 // gas accepts arguments separated by whitespace, except on Darwin
1693 if (!IsDarwin)
1694 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001695
1696 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001697 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1698 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001699 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001700 }
1701
1702 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1703 // Spaces and commas cannot be mixed to delimit parameters
1704 if (ArgumentDelimiter == AsmToken::Eof)
1705 ArgumentDelimiter = AsmToken::Comma;
1706 else if (ArgumentDelimiter != AsmToken::Comma) {
1707 Lexer.setSkipSpace(true);
1708 return TokError("expected ' ' for macro argument separator");
1709 }
1710 break;
1711 }
1712
1713 if (Lexer.is(AsmToken::Space)) {
1714 Lex(); // Eat spaces
1715
1716 // Spaces can delimit parameters, but could also be part an expression.
1717 // If the token after a space is an operator, add the token and the next
1718 // one into this argument
1719 if (ArgumentDelimiter == AsmToken::Space ||
1720 ArgumentDelimiter == AsmToken::Eof) {
1721 if (IsOperator(Lexer.getKind())) {
1722 // Check to see whether the token is used as an operator,
1723 // or part of an identifier
1724 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1725 if (*NextChar == ' ')
1726 AddTokens = 2;
1727 }
1728
1729 if (!AddTokens && ParenLevel == 0) {
1730 if (ArgumentDelimiter == AsmToken::Eof &&
1731 !IsOperator(Lexer.getKind()))
1732 ArgumentDelimiter = AsmToken::Space;
1733 break;
1734 }
1735 }
1736 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001737
1738 // HandleMacroEntry relies on not advancing the lexer here
1739 // to be able to fill in the remaining default parameter values
1740 if (Lexer.is(AsmToken::EndOfStatement))
1741 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001742
1743 // Adjust the current parentheses level.
1744 if (Lexer.is(AsmToken::LParen))
1745 ++ParenLevel;
1746 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1747 --ParenLevel;
1748
1749 // Append the token to the current argument list.
1750 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001751 if (AddTokens)
1752 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001753 Lex();
1754 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001755
1756 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001757 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001758 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001759 return false;
1760}
1761
1762// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001763bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001764 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001765 // Argument delimiter is initially unknown. It will be set by
1766 // ParseMacroArgument()
1767 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001768
1769 // Parse two kinds of macro invocations:
1770 // - macros defined without any parameters accept an arbitrary number of them
1771 // - macros defined with parameters accept at most that many of them
1772 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1773 ++Parameter) {
1774 MacroArgument MA;
1775
Preston Gurd7b6f2032012-09-19 20:36:12 +00001776 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001777 return true;
1778
Preston Gurd6c9176a2012-09-19 20:29:04 +00001779 if (!MA.empty() || !NParameters)
1780 A.push_back(MA);
1781 else if (NParameters) {
1782 if (!M->Parameters[Parameter].second.empty())
1783 A.push_back(M->Parameters[Parameter].second);
1784 }
Jim Grosbach97146442012-07-30 22:44:17 +00001785
Preston Gurd6c9176a2012-09-19 20:29:04 +00001786 // At the end of the statement, fill in remaining arguments that have
1787 // default values. If there aren't any, then the next argument is
1788 // required but missing
1789 if (Lexer.is(AsmToken::EndOfStatement)) {
1790 if (NParameters && Parameter < NParameters - 1) {
1791 if (M->Parameters[Parameter + 1].second.empty())
1792 return TokError("macro argument '" +
1793 Twine(M->Parameters[Parameter + 1].first) +
1794 "' is missing");
1795 else
1796 continue;
1797 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001798 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001799 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001800
1801 if (Lexer.is(AsmToken::Comma))
1802 Lex();
1803 }
1804 return TokError("Too many arguments");
1805}
1806
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001807bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1808 const Macro *M) {
1809 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1810 // this, although we should protect against infinite loops.
1811 if (ActiveMacros.size() == 20)
1812 return TokError("macros cannot be nested more than 20 levels deep");
1813
Rafael Espindola8a403d32012-08-08 14:51:03 +00001814 MacroArguments A;
1815 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001816 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001817
Jim Grosbach97146442012-07-30 22:44:17 +00001818 // Remove any trailing empty arguments. Do this after-the-fact as we have
1819 // to keep empty arguments in the middle of the list or positionality
1820 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001821 while (!A.empty() && A.back().empty())
1822 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001823
Rafael Espindola65366442011-06-05 02:43:45 +00001824 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1825 // to hold the macro body with substitutions.
1826 SmallString<256> Buf;
1827 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001828 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001829
Rafael Espindola8a403d32012-08-08 14:51:03 +00001830 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001831 return true;
1832
Rafael Espindola761cb062012-06-03 23:57:14 +00001833 // We include the .endmacro in the buffer as our queue to exit the macro
1834 // instantiation.
1835 OS << ".endmacro\n";
1836
Rafael Espindola65366442011-06-05 02:43:45 +00001837 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001838 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001839
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001840 // Create the macro instantiation object and add to the current macro
1841 // instantiation stack.
1842 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001843 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001844 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001845 ActiveMacros.push_back(MI);
1846
1847 // Jump to the macro instantiation and prime the lexer.
1848 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1849 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1850 Lex();
1851
1852 return false;
1853}
1854
1855void AsmParser::HandleMacroExit() {
1856 // Jump to the EndOfStatement we should return to, and consume it.
1857 JumpToLoc(ActiveMacros.back()->ExitLoc);
1858 Lex();
1859
1860 // Pop the instantiation entry.
1861 delete ActiveMacros.back();
1862 ActiveMacros.pop_back();
1863}
1864
Rafael Espindolae71cc862012-01-28 05:57:00 +00001865static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001866 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001867 case MCExpr::Binary: {
1868 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1869 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001870 break;
1871 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001872 case MCExpr::Target:
1873 case MCExpr::Constant:
1874 return false;
1875 case MCExpr::SymbolRef: {
1876 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001877 if (S.isVariable())
1878 return IsUsedIn(Sym, S.getVariableValue());
1879 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001880 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001881 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001882 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001883 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001884
1885 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001886}
1887
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001888bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1889 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001890 // FIXME: Use better location, we should use proper tokens.
1891 SMLoc EqualLoc = Lexer.getLoc();
1892
Daniel Dunbar821e3332009-08-31 08:09:28 +00001893 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001894 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001895 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001896
Rafael Espindolae71cc862012-01-28 05:57:00 +00001897 // Note: we don't count b as used in "a = b". This is to allow
1898 // a = b
1899 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001900
Daniel Dunbar3f872332009-07-28 16:08:33 +00001901 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001902 return TokError("unexpected token in assignment");
1903
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001904 // Error on assignment to '.'.
1905 if (Name == ".") {
1906 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1907 "(use '.space' or '.org').)"));
1908 }
1909
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001910 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001911 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001912
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001913 // Validate that the LHS is allowed to be a variable (either it has not been
1914 // used as a symbol, or it is an absolute symbol).
1915 MCSymbol *Sym = getContext().LookupSymbol(Name);
1916 if (Sym) {
1917 // Diagnose assignment to a label.
1918 //
1919 // FIXME: Diagnostics. Note the location of the definition as a label.
1920 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001921 if (IsUsedIn(Sym, Value))
1922 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1923 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001924 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001925 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1926 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001927 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001928 return Error(EqualLoc, "redefinition of '" + Name + "'");
1929 else if (!Sym->isVariable())
1930 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001931 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001932 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1933 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001934
1935 // Don't count these checks as uses.
1936 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001937 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001938 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001939
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001940 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001941
1942 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001943 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001944 if (NoDeadStrip)
1945 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1946
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001947
1948 return false;
1949}
1950
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001951/// ParseIdentifier:
1952/// ::= identifier
1953/// ::= string
1954bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001955 // The assembler has relaxed rules for accepting identifiers, in particular we
1956 // allow things like '.globl $foo', which would normally be separate
1957 // tokens. At this level, we have already lexed so we cannot (currently)
1958 // handle this as a context dependent token, instead we detect adjacent tokens
1959 // and return the combined identifier.
1960 if (Lexer.is(AsmToken::Dollar)) {
1961 SMLoc DollarLoc = getLexer().getLoc();
1962
1963 // Consume the dollar sign, and check for a following identifier.
1964 Lex();
1965 if (Lexer.isNot(AsmToken::Identifier))
1966 return true;
1967
1968 // We have a '$' followed by an identifier, make sure they are adjacent.
1969 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1970 return true;
1971
1972 // Construct the joined identifier and consume the token.
1973 Res = StringRef(DollarLoc.getPointer(),
1974 getTok().getIdentifier().size() + 1);
1975 Lex();
1976 return false;
1977 }
1978
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001979 if (Lexer.isNot(AsmToken::Identifier) &&
1980 Lexer.isNot(AsmToken::String))
1981 return true;
1982
Sean Callanan18b83232010-01-19 21:44:56 +00001983 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001984
Sean Callanan79ed1a82010-01-19 20:22:31 +00001985 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001986
1987 return false;
1988}
1989
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001990/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001991/// ::= .equ identifier ',' expression
1992/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001993/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001994bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001995 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001996
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001997 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001998 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001999
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002000 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002001 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002002 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002003
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002004 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002005}
2006
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002007bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002008 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002009
2010 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002011 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002012 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2013 if (Str[i] != '\\') {
2014 Data += Str[i];
2015 continue;
2016 }
2017
2018 // Recognize escaped characters. Note that this escape semantics currently
2019 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2020 ++i;
2021 if (i == e)
2022 return TokError("unexpected backslash at end of string");
2023
2024 // Recognize octal sequences.
2025 if ((unsigned) (Str[i] - '0') <= 7) {
2026 // Consume up to three octal characters.
2027 unsigned Value = Str[i] - '0';
2028
2029 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2030 ++i;
2031 Value = Value * 8 + (Str[i] - '0');
2032
2033 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2034 ++i;
2035 Value = Value * 8 + (Str[i] - '0');
2036 }
2037 }
2038
2039 if (Value > 255)
2040 return TokError("invalid octal escape sequence (out of range)");
2041
2042 Data += (unsigned char) Value;
2043 continue;
2044 }
2045
2046 // Otherwise recognize individual escapes.
2047 switch (Str[i]) {
2048 default:
2049 // Just reject invalid escape sequences for now.
2050 return TokError("invalid escape sequence (unrecognized character)");
2051
2052 case 'b': Data += '\b'; break;
2053 case 'f': Data += '\f'; break;
2054 case 'n': Data += '\n'; break;
2055 case 'r': Data += '\r'; break;
2056 case 't': Data += '\t'; break;
2057 case '"': Data += '"'; break;
2058 case '\\': Data += '\\'; break;
2059 }
2060 }
2061
2062 return false;
2063}
2064
Daniel Dunbara0d14262009-06-24 23:30:00 +00002065/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002066/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2067bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002068 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002069 CheckForValidSection();
2070
Daniel Dunbara0d14262009-06-24 23:30:00 +00002071 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002072 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002073 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002074
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002075 std::string Data;
2076 if (ParseEscapedString(Data))
2077 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002078
2079 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002080 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002081 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2082
Sean Callanan79ed1a82010-01-19 20:22:31 +00002083 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002084
2085 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002086 break;
2087
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002088 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002089 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002090 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002091 }
2092 }
2093
Sean Callanan79ed1a82010-01-19 20:22:31 +00002094 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002095 return false;
2096}
2097
2098/// ParseDirectiveValue
2099/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2100bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002101 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002102 CheckForValidSection();
2103
Daniel Dunbara0d14262009-06-24 23:30:00 +00002104 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002105 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002106 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002107 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002108 return true;
2109
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002110 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002111 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2112 assert(Size <= 8 && "Invalid size");
2113 uint64_t IntValue = MCE->getValue();
2114 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2115 return Error(ExprLoc, "literal value out of range for directive");
2116 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2117 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002118 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002119
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002120 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002121 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002122
Daniel Dunbara0d14262009-06-24 23:30:00 +00002123 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002124 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002125 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002126 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002127 }
2128 }
2129
Sean Callanan79ed1a82010-01-19 20:22:31 +00002130 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002131 return false;
2132}
2133
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002134/// ParseDirectiveRealValue
2135/// ::= (.single | .double) [ expression (, expression)* ]
2136bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2137 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2138 CheckForValidSection();
2139
2140 for (;;) {
2141 // We don't truly support arithmetic on floating point expressions, so we
2142 // have to manually parse unary prefixes.
2143 bool IsNeg = false;
2144 if (getLexer().is(AsmToken::Minus)) {
2145 Lex();
2146 IsNeg = true;
2147 } else if (getLexer().is(AsmToken::Plus))
2148 Lex();
2149
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002150 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002151 getLexer().isNot(AsmToken::Real) &&
2152 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002153 return TokError("unexpected token in directive");
2154
2155 // Convert to an APFloat.
2156 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002157 StringRef IDVal = getTok().getString();
2158 if (getLexer().is(AsmToken::Identifier)) {
2159 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2160 Value = APFloat::getInf(Semantics);
2161 else if (!IDVal.compare_lower("nan"))
2162 Value = APFloat::getNaN(Semantics, false, ~0);
2163 else
2164 return TokError("invalid floating point literal");
2165 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002166 APFloat::opInvalidOp)
2167 return TokError("invalid floating point literal");
2168 if (IsNeg)
2169 Value.changeSign();
2170
2171 // Consume the numeric token.
2172 Lex();
2173
2174 // Emit the value as an integer.
2175 APInt AsInt = Value.bitcastToAPInt();
2176 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2177 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2178
2179 if (getLexer().is(AsmToken::EndOfStatement))
2180 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002181
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002182 if (getLexer().isNot(AsmToken::Comma))
2183 return TokError("unexpected token in directive");
2184 Lex();
2185 }
2186 }
2187
2188 Lex();
2189 return false;
2190}
2191
Daniel Dunbara0d14262009-06-24 23:30:00 +00002192/// ParseDirectiveSpace
2193/// ::= .space expression [ , expression ]
2194bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002195 CheckForValidSection();
2196
Daniel Dunbara0d14262009-06-24 23:30:00 +00002197 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002198 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002199 return true;
2200
2201 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002202 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2203 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002204 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002205 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002206
Daniel Dunbar475839e2009-06-29 20:37:27 +00002207 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002208 return true;
2209
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002210 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002211 return TokError("unexpected token in '.space' directive");
2212 }
2213
Sean Callanan79ed1a82010-01-19 20:22:31 +00002214 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215
2216 if (NumBytes <= 0)
2217 return TokError("invalid number of bytes in '.space' directive");
2218
2219 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002220 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221
2222 return false;
2223}
2224
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002225/// ParseDirectiveZero
2226/// ::= .zero expression
2227bool AsmParser::ParseDirectiveZero() {
2228 CheckForValidSection();
2229
2230 int64_t NumBytes;
2231 if (ParseAbsoluteExpression(NumBytes))
2232 return true;
2233
Rafael Espindolae452b172010-10-05 19:42:57 +00002234 int64_t Val = 0;
2235 if (getLexer().is(AsmToken::Comma)) {
2236 Lex();
2237 if (ParseAbsoluteExpression(Val))
2238 return true;
2239 }
2240
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002241 if (getLexer().isNot(AsmToken::EndOfStatement))
2242 return TokError("unexpected token in '.zero' directive");
2243
2244 Lex();
2245
Rafael Espindolae452b172010-10-05 19:42:57 +00002246 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002247
2248 return false;
2249}
2250
Daniel Dunbara0d14262009-06-24 23:30:00 +00002251/// ParseDirectiveFill
2252/// ::= .fill expression , expression , expression
2253bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002254 CheckForValidSection();
2255
Daniel Dunbara0d14262009-06-24 23:30:00 +00002256 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002257 if (ParseAbsoluteExpression(NumValues))
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 FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002265 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002266 return true;
2267
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002268 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002270 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002271
Daniel Dunbara0d14262009-06-24 23:30:00 +00002272 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002273 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 return true;
2275
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002276 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002277 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002278
Sean Callanan79ed1a82010-01-19 20:22:31 +00002279 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002280
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002281 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2282 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002283
2284 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002285 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002286
2287 return false;
2288}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002289
2290/// ParseDirectiveOrg
2291/// ::= .org expression [ , expression ]
2292bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002293 CheckForValidSection();
2294
Daniel Dunbar821e3332009-08-31 08:09:28 +00002295 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002296 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002297 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002298 return true;
2299
2300 // Parse optional fill expression.
2301 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002302 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2303 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002304 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002305 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002306
Daniel Dunbar475839e2009-06-29 20:37:27 +00002307 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002308 return true;
2309
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002310 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002311 return TokError("unexpected token in '.org' directive");
2312 }
2313
Sean Callanan79ed1a82010-01-19 20:22:31 +00002314 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002315
Jim Grosbachebd4c052012-01-27 00:37:08 +00002316 // Only limited forms of relocatable expressions are accepted here, it
2317 // has to be relative to the current section. The streamer will return
2318 // 'true' if the expression wasn't evaluatable.
2319 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2320 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002321
2322 return false;
2323}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002324
2325/// ParseDirectiveAlign
2326/// ::= {.align, ...} expression [ , expression [ , expression ]]
2327bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002328 CheckForValidSection();
2329
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002330 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002331 int64_t Alignment;
2332 if (ParseAbsoluteExpression(Alignment))
2333 return true;
2334
2335 SMLoc MaxBytesLoc;
2336 bool HasFillExpr = false;
2337 int64_t FillExpr = 0;
2338 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002339 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2340 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002341 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002342 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002343
2344 // The fill expression can be omitted while specifying a maximum number of
2345 // alignment bytes, e.g:
2346 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002347 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002348 HasFillExpr = true;
2349 if (ParseAbsoluteExpression(FillExpr))
2350 return true;
2351 }
2352
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002353 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2354 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002355 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002356 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002357
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002358 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002359 if (ParseAbsoluteExpression(MaxBytesToFill))
2360 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002361
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002362 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002363 return TokError("unexpected token in directive");
2364 }
2365 }
2366
Sean Callanan79ed1a82010-01-19 20:22:31 +00002367 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002368
Daniel Dunbar648ac512010-05-17 21:54:30 +00002369 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002370 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002371
2372 // Compute alignment in bytes.
2373 if (IsPow2) {
2374 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002375 if (Alignment >= 32) {
2376 Error(AlignmentLoc, "invalid alignment value");
2377 Alignment = 31;
2378 }
2379
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002380 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002381 }
2382
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002383 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002384 if (MaxBytesLoc.isValid()) {
2385 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002386 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2387 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002388 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002389 }
2390
2391 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002392 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2393 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002394 MaxBytesToFill = 0;
2395 }
2396 }
2397
Daniel Dunbar648ac512010-05-17 21:54:30 +00002398 // Check whether we should use optimal code alignment for this .align
2399 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002400 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002401 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2402 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002403 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002404 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002405 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002406 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2407 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002408 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002409
2410 return false;
2411}
2412
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002413/// ParseDirectiveSymbolAttribute
2414/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002415bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002417 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002418 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002419 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002420
2421 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002422 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002423
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002424 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002425
Jim Grosbach10ec6502011-09-15 17:56:49 +00002426 // Assembler local symbols don't make any sense here. Complain loudly.
2427 if (Sym->isTemporary())
2428 return Error(Loc, "non-local symbol required in directive");
2429
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002430 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002431
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002432 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002433 break;
2434
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002435 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002436 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002437 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002438 }
2439 }
2440
Sean Callanan79ed1a82010-01-19 20:22:31 +00002441 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002442 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002443}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002444
2445/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002446/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2447bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002448 CheckForValidSection();
2449
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002450 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002451 StringRef Name;
2452 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002453 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002454
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002455 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002456 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002457
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002458 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002459 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002460 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002461
2462 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002463 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002464 if (ParseAbsoluteExpression(Size))
2465 return true;
2466
2467 int64_t Pow2Alignment = 0;
2468 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002469 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002470 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002471 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002472 if (ParseAbsoluteExpression(Pow2Alignment))
2473 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002474
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002475 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2476 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002477 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2478
Chris Lattner258281d2010-01-19 06:22:22 +00002479 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002480 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2481 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002482 if (!isPowerOf2_64(Pow2Alignment))
2483 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2484 Pow2Alignment = Log2_64(Pow2Alignment);
2485 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002486 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002487
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002488 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002489 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002490
Sean Callanan79ed1a82010-01-19 20:22:31 +00002491 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002492
Chris Lattner1fc3d752009-07-09 17:25:12 +00002493 // NOTE: a size of zero for a .comm should create a undefined symbol
2494 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002495 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002496 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2497 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002498
Eric Christopherc260a3e2010-05-14 01:38:54 +00002499 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002500 // may internally end up wanting an alignment in bytes.
2501 // FIXME: Diagnose overflow.
2502 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002503 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2504 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002505
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002506 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002507 return Error(IDLoc, "invalid symbol redefinition");
2508
Chris Lattner1fc3d752009-07-09 17:25:12 +00002509 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002510 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002511 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002512 return false;
2513 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002514
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002515 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002516 return false;
2517}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002518
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002519/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002520/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002521bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002522 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002523 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002524
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002525 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002526 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002527 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002528
Sean Callanan79ed1a82010-01-19 20:22:31 +00002529 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002530
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002531 if (Str.empty())
2532 Error(Loc, ".abort detected. Assembly stopping.");
2533 else
2534 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002535 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002536
2537 return false;
2538}
Kevin Enderby71148242009-07-14 21:35:03 +00002539
Kevin Enderby1f049b22009-07-14 23:21:55 +00002540/// ParseDirectiveInclude
2541/// ::= .include "filename"
2542bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002543 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002544 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002545
Sean Callanan18b83232010-01-19 21:44:56 +00002546 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002547 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002548 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002549
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002550 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002551 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002552
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002553 // Strip the quotes.
2554 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002555
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002556 // Attempt to switch the lexer to the included file before consuming the end
2557 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002558 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002559 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002560 return true;
2561 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002562
2563 return false;
2564}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002565
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002566/// ParseDirectiveIncbin
2567/// ::= .incbin "filename"
2568bool AsmParser::ParseDirectiveIncbin() {
2569 if (getLexer().isNot(AsmToken::String))
2570 return TokError("expected string in '.incbin' directive");
2571
2572 std::string Filename = getTok().getString();
2573 SMLoc IncbinLoc = getLexer().getLoc();
2574 Lex();
2575
2576 if (getLexer().isNot(AsmToken::EndOfStatement))
2577 return TokError("unexpected token in '.incbin' directive");
2578
2579 // Strip the quotes.
2580 Filename = Filename.substr(1, Filename.size()-2);
2581
2582 // Attempt to process the included file.
2583 if (ProcessIncbinFile(Filename)) {
2584 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2585 return true;
2586 }
2587
2588 return false;
2589}
2590
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002591/// ParseDirectiveIf
2592/// ::= .if expression
2593bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002594 TheCondStack.push_back(TheCondState);
2595 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002596 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002597 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002598 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002599 int64_t ExprValue;
2600 if (ParseAbsoluteExpression(ExprValue))
2601 return true;
2602
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002603 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002604 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002605
Sean Callanan79ed1a82010-01-19 20:22:31 +00002606 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002607
2608 TheCondState.CondMet = ExprValue;
2609 TheCondState.Ignore = !TheCondState.CondMet;
2610 }
2611
2612 return false;
2613}
2614
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002615/// ParseDirectiveIfb
2616/// ::= .ifb string
2617bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2618 TheCondStack.push_back(TheCondState);
2619 TheCondState.TheCond = AsmCond::IfCond;
2620
Benjamin Kramer29739e72012-05-12 16:52:21 +00002621 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002622 EatToEndOfStatement();
2623 } else {
2624 StringRef Str = ParseStringToEndOfStatement();
2625
2626 if (getLexer().isNot(AsmToken::EndOfStatement))
2627 return TokError("unexpected token in '.ifb' directive");
2628
2629 Lex();
2630
2631 TheCondState.CondMet = ExpectBlank == Str.empty();
2632 TheCondState.Ignore = !TheCondState.CondMet;
2633 }
2634
2635 return false;
2636}
2637
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002638/// ParseDirectiveIfc
2639/// ::= .ifc string1, string2
2640bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2641 TheCondStack.push_back(TheCondState);
2642 TheCondState.TheCond = AsmCond::IfCond;
2643
Benjamin Kramer29739e72012-05-12 16:52:21 +00002644 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002645 EatToEndOfStatement();
2646 } else {
2647 StringRef Str1 = ParseStringToComma();
2648
2649 if (getLexer().isNot(AsmToken::Comma))
2650 return TokError("unexpected token in '.ifc' directive");
2651
2652 Lex();
2653
2654 StringRef Str2 = ParseStringToEndOfStatement();
2655
2656 if (getLexer().isNot(AsmToken::EndOfStatement))
2657 return TokError("unexpected token in '.ifc' directive");
2658
2659 Lex();
2660
2661 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2662 TheCondState.Ignore = !TheCondState.CondMet;
2663 }
2664
2665 return false;
2666}
2667
2668/// ParseDirectiveIfdef
2669/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002670bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2671 StringRef Name;
2672 TheCondStack.push_back(TheCondState);
2673 TheCondState.TheCond = AsmCond::IfCond;
2674
2675 if (TheCondState.Ignore) {
2676 EatToEndOfStatement();
2677 } else {
2678 if (ParseIdentifier(Name))
2679 return TokError("expected identifier after '.ifdef'");
2680
2681 Lex();
2682
2683 MCSymbol *Sym = getContext().LookupSymbol(Name);
2684
2685 if (expect_defined)
2686 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2687 else
2688 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2689 TheCondState.Ignore = !TheCondState.CondMet;
2690 }
2691
2692 return false;
2693}
2694
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002695/// ParseDirectiveElseIf
2696/// ::= .elseif expression
2697bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2698 if (TheCondState.TheCond != AsmCond::IfCond &&
2699 TheCondState.TheCond != AsmCond::ElseIfCond)
2700 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2701 " an .elseif");
2702 TheCondState.TheCond = AsmCond::ElseIfCond;
2703
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002704 bool LastIgnoreState = false;
2705 if (!TheCondStack.empty())
2706 LastIgnoreState = TheCondStack.back().Ignore;
2707 if (LastIgnoreState || TheCondState.CondMet) {
2708 TheCondState.Ignore = true;
2709 EatToEndOfStatement();
2710 }
2711 else {
2712 int64_t ExprValue;
2713 if (ParseAbsoluteExpression(ExprValue))
2714 return true;
2715
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002716 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002717 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002718
Sean Callanan79ed1a82010-01-19 20:22:31 +00002719 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002720 TheCondState.CondMet = ExprValue;
2721 TheCondState.Ignore = !TheCondState.CondMet;
2722 }
2723
2724 return false;
2725}
2726
2727/// ParseDirectiveElse
2728/// ::= .else
2729bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002730 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002731 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002732
Sean Callanan79ed1a82010-01-19 20:22:31 +00002733 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002734
2735 if (TheCondState.TheCond != AsmCond::IfCond &&
2736 TheCondState.TheCond != AsmCond::ElseIfCond)
2737 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2738 ".elseif");
2739 TheCondState.TheCond = AsmCond::ElseCond;
2740 bool LastIgnoreState = false;
2741 if (!TheCondStack.empty())
2742 LastIgnoreState = TheCondStack.back().Ignore;
2743 if (LastIgnoreState || TheCondState.CondMet)
2744 TheCondState.Ignore = true;
2745 else
2746 TheCondState.Ignore = false;
2747
2748 return false;
2749}
2750
2751/// ParseDirectiveEndIf
2752/// ::= .endif
2753bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002754 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002755 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002756
Sean Callanan79ed1a82010-01-19 20:22:31 +00002757 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002758
2759 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2760 TheCondStack.empty())
2761 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2762 ".else");
2763 if (!TheCondStack.empty()) {
2764 TheCondState = TheCondStack.back();
2765 TheCondStack.pop_back();
2766 }
2767
2768 return false;
2769}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002770
2771/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002772/// ::= .file [number] filename
2773/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002774bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002775 // FIXME: I'm not sure what this is.
2776 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002777 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002778 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002779 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002780 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002781
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002782 if (FileNumber < 1)
2783 return TokError("file number less than one");
2784 }
2785
Daniel Dunbareceec052010-07-12 17:45:27 +00002786 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002787 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002788
Nick Lewycky44d798d2011-10-17 23:05:28 +00002789 // Usually the directory and filename together, otherwise just the directory.
2790 StringRef Path = getTok().getString();
2791 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002792 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002793
Nick Lewycky44d798d2011-10-17 23:05:28 +00002794 StringRef Directory;
2795 StringRef Filename;
2796 if (getLexer().is(AsmToken::String)) {
2797 if (FileNumber == -1)
2798 return TokError("explicit path specified, but no file number");
2799 Filename = getTok().getString();
2800 Filename = Filename.substr(1, Filename.size()-2);
2801 Directory = Path;
2802 Lex();
2803 } else {
2804 Filename = Path;
2805 }
2806
Daniel Dunbareceec052010-07-12 17:45:27 +00002807 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002808 return TokError("unexpected token in '.file' directive");
2809
Chris Lattnerd32e8032010-01-25 19:02:58 +00002810 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002811 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002812 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002813 if (getContext().getGenDwarfForAssembly() == true)
2814 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2815 "used to generate dwarf debug info for assembly code");
2816
Nick Lewycky44d798d2011-10-17 23:05:28 +00002817 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002818 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002819 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002820
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002821 return false;
2822}
2823
2824/// ParseDirectiveLine
2825/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002826bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002827 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2828 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002829 return TokError("unexpected token in '.line' directive");
2830
Sean Callanan18b83232010-01-19 21:44:56 +00002831 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002832 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002833 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002834
2835 // FIXME: Do something with the .line.
2836 }
2837
Daniel Dunbareceec052010-07-12 17:45:27 +00002838 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002839 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002840
2841 return false;
2842}
2843
2844
2845/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002846/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002847/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2848/// The first number is a file number, must have been previously assigned with
2849/// a .file directive, the second number is the line number and optionally the
2850/// third number is a column position (zero if not specified). The remaining
2851/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002852bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002853
Daniel Dunbareceec052010-07-12 17:45:27 +00002854 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002855 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002856 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002857 if (FileNumber < 1)
2858 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002859 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002860 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002861 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002862
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002863 int64_t LineNumber = 0;
2864 if (getLexer().is(AsmToken::Integer)) {
2865 LineNumber = getTok().getIntVal();
2866 if (LineNumber < 1)
2867 return TokError("line number less than one in '.loc' directive");
2868 Lex();
2869 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002870
2871 int64_t ColumnPos = 0;
2872 if (getLexer().is(AsmToken::Integer)) {
2873 ColumnPos = getTok().getIntVal();
2874 if (ColumnPos < 0)
2875 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002876 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002877 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002878
Kevin Enderbyc0957932010-09-30 16:52:03 +00002879 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002880 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002881 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002882 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2883 for (;;) {
2884 if (getLexer().is(AsmToken::EndOfStatement))
2885 break;
2886
2887 StringRef Name;
2888 SMLoc Loc = getTok().getLoc();
2889 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002890 return TokError("unexpected token in '.loc' directive");
2891
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002892 if (Name == "basic_block")
2893 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2894 else if (Name == "prologue_end")
2895 Flags |= DWARF2_FLAG_PROLOGUE_END;
2896 else if (Name == "epilogue_begin")
2897 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2898 else if (Name == "is_stmt") {
2899 SMLoc Loc = getTok().getLoc();
2900 const MCExpr *Value;
2901 if (getParser().ParseExpression(Value))
2902 return true;
2903 // The expression must be the constant 0 or 1.
2904 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2905 int Value = MCE->getValue();
2906 if (Value == 0)
2907 Flags &= ~DWARF2_FLAG_IS_STMT;
2908 else if (Value == 1)
2909 Flags |= DWARF2_FLAG_IS_STMT;
2910 else
2911 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002912 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002913 else {
2914 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2915 }
2916 }
2917 else if (Name == "isa") {
2918 SMLoc Loc = getTok().getLoc();
2919 const MCExpr *Value;
2920 if (getParser().ParseExpression(Value))
2921 return true;
2922 // The expression must be a constant greater or equal to 0.
2923 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2924 int Value = MCE->getValue();
2925 if (Value < 0)
2926 return Error(Loc, "isa number less than zero");
2927 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002928 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002929 else {
2930 return Error(Loc, "isa number not a constant value");
2931 }
2932 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002933 else if (Name == "discriminator") {
2934 if (getParser().ParseAbsoluteExpression(Discriminator))
2935 return true;
2936 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002937 else {
2938 return Error(Loc, "unknown sub-directive in '.loc' directive");
2939 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002940
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002941 if (getLexer().is(AsmToken::EndOfStatement))
2942 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002943 }
2944 }
2945
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002946 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002947 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002948
2949 return false;
2950}
2951
Daniel Dunbar138abae2010-10-16 04:56:42 +00002952/// ParseDirectiveStabs
2953/// ::= .stabs string, number, number, number
2954bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2955 SMLoc DirectiveLoc) {
2956 return TokError("unsupported directive '" + Directive + "'");
2957}
2958
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002959/// ParseDirectiveCFISections
2960/// ::= .cfi_sections section [, section]
2961bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2962 SMLoc DirectiveLoc) {
2963 StringRef Name;
2964 bool EH = false;
2965 bool Debug = false;
2966
2967 if (getParser().ParseIdentifier(Name))
2968 return TokError("Expected an identifier");
2969
2970 if (Name == ".eh_frame")
2971 EH = true;
2972 else if (Name == ".debug_frame")
2973 Debug = true;
2974
2975 if (getLexer().is(AsmToken::Comma)) {
2976 Lex();
2977
2978 if (getParser().ParseIdentifier(Name))
2979 return TokError("Expected an identifier");
2980
2981 if (Name == ".eh_frame")
2982 EH = true;
2983 else if (Name == ".debug_frame")
2984 Debug = true;
2985 }
2986
2987 getStreamer().EmitCFISections(EH, Debug);
2988
2989 return false;
2990}
2991
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002992/// ParseDirectiveCFIStartProc
2993/// ::= .cfi_startproc
2994bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2995 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002996 getStreamer().EmitCFIStartProc();
2997 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002998}
2999
3000/// ParseDirectiveCFIEndProc
3001/// ::= .cfi_endproc
3002bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003003 getStreamer().EmitCFIEndProc();
3004 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003005}
3006
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003007/// ParseRegisterOrRegisterNumber - parse register name or number.
3008bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3009 SMLoc DirectiveLoc) {
3010 unsigned RegNo;
3011
Jim Grosbach6f888a82011-06-02 17:14:04 +00003012 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003013 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3014 DirectiveLoc))
3015 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003016 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003017 } else
3018 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003019
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003020 return false;
3021}
3022
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003023/// ParseDirectiveCFIDefCfa
3024/// ::= .cfi_def_cfa register, offset
3025bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3026 SMLoc DirectiveLoc) {
3027 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003028 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003029 return true;
3030
3031 if (getLexer().isNot(AsmToken::Comma))
3032 return TokError("unexpected token in directive");
3033 Lex();
3034
3035 int64_t Offset = 0;
3036 if (getParser().ParseAbsoluteExpression(Offset))
3037 return true;
3038
Rafael Espindola066c2f42011-04-12 23:59:07 +00003039 getStreamer().EmitCFIDefCfa(Register, Offset);
3040 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003041}
3042
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003043/// ParseDirectiveCFIDefCfaOffset
3044/// ::= .cfi_def_cfa_offset offset
3045bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3046 SMLoc DirectiveLoc) {
3047 int64_t Offset = 0;
3048 if (getParser().ParseAbsoluteExpression(Offset))
3049 return true;
3050
Rafael Espindola066c2f42011-04-12 23:59:07 +00003051 getStreamer().EmitCFIDefCfaOffset(Offset);
3052 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003053}
3054
3055/// ParseDirectiveCFIAdjustCfaOffset
3056/// ::= .cfi_adjust_cfa_offset adjustment
3057bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3058 SMLoc DirectiveLoc) {
3059 int64_t Adjustment = 0;
3060 if (getParser().ParseAbsoluteExpression(Adjustment))
3061 return true;
3062
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003063 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3064 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003065}
3066
3067/// ParseDirectiveCFIDefCfaRegister
3068/// ::= .cfi_def_cfa_register register
3069bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3070 SMLoc DirectiveLoc) {
3071 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003072 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003073 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003074
Rafael Espindola066c2f42011-04-12 23:59:07 +00003075 getStreamer().EmitCFIDefCfaRegister(Register);
3076 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003077}
3078
3079/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003080/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003081bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3082 int64_t Register = 0;
3083 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003084
3085 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003086 return true;
3087
3088 if (getLexer().isNot(AsmToken::Comma))
3089 return TokError("unexpected token in directive");
3090 Lex();
3091
3092 if (getParser().ParseAbsoluteExpression(Offset))
3093 return true;
3094
Rafael Espindola066c2f42011-04-12 23:59:07 +00003095 getStreamer().EmitCFIOffset(Register, Offset);
3096 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003097}
3098
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003099/// ParseDirectiveCFIRelOffset
3100/// ::= .cfi_rel_offset register, offset
3101bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3102 SMLoc DirectiveLoc) {
3103 int64_t Register = 0;
3104
3105 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3106 return true;
3107
3108 if (getLexer().isNot(AsmToken::Comma))
3109 return TokError("unexpected token in directive");
3110 Lex();
3111
3112 int64_t Offset = 0;
3113 if (getParser().ParseAbsoluteExpression(Offset))
3114 return true;
3115
Rafael Espindola25f492e2011-04-12 16:12:03 +00003116 getStreamer().EmitCFIRelOffset(Register, Offset);
3117 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003118}
3119
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003120static bool isValidEncoding(int64_t Encoding) {
3121 if (Encoding & ~0xff)
3122 return false;
3123
3124 if (Encoding == dwarf::DW_EH_PE_omit)
3125 return true;
3126
3127 const unsigned Format = Encoding & 0xf;
3128 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3129 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3130 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3131 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3132 return false;
3133
Rafael Espindolacaf11582010-12-29 04:31:26 +00003134 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003135 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003136 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003137 return false;
3138
3139 return true;
3140}
3141
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003142/// ParseDirectiveCFIPersonalityOrLsda
3143/// ::= .cfi_personality encoding, [symbol_name]
3144/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003145bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003146 SMLoc DirectiveLoc) {
3147 int64_t Encoding = 0;
3148 if (getParser().ParseAbsoluteExpression(Encoding))
3149 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003150 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003151 return false;
3152
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003153 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003154 return TokError("unsupported encoding.");
3155
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003156 if (getLexer().isNot(AsmToken::Comma))
3157 return TokError("unexpected token in directive");
3158 Lex();
3159
3160 StringRef Name;
3161 if (getParser().ParseIdentifier(Name))
3162 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003163
3164 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3165
3166 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003167 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003168 else {
3169 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003170 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003171 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003172 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003173}
3174
Rafael Espindolafe024d02010-12-28 18:36:23 +00003175/// ParseDirectiveCFIRememberState
3176/// ::= .cfi_remember_state
3177bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3178 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003179 getStreamer().EmitCFIRememberState();
3180 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003181}
3182
3183/// ParseDirectiveCFIRestoreState
3184/// ::= .cfi_remember_state
3185bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3186 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003187 getStreamer().EmitCFIRestoreState();
3188 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003189}
3190
Rafael Espindolac5754392011-04-12 15:31:05 +00003191/// ParseDirectiveCFISameValue
3192/// ::= .cfi_same_value register
3193bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3194 SMLoc DirectiveLoc) {
3195 int64_t Register = 0;
3196
3197 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3198 return true;
3199
3200 getStreamer().EmitCFISameValue(Register);
3201
3202 return false;
3203}
3204
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003205/// ParseDirectiveCFIRestore
3206/// ::= .cfi_restore register
3207bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003208 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003209 int64_t Register = 0;
3210 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3211 return true;
3212
3213 getStreamer().EmitCFIRestore(Register);
3214
3215 return false;
3216}
3217
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003218/// ParseDirectiveCFIEscape
3219/// ::= .cfi_escape expression[,...]
3220bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003221 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003222 std::string Values;
3223 int64_t CurrValue;
3224 if (getParser().ParseAbsoluteExpression(CurrValue))
3225 return true;
3226
3227 Values.push_back((uint8_t)CurrValue);
3228
3229 while (getLexer().is(AsmToken::Comma)) {
3230 Lex();
3231
3232 if (getParser().ParseAbsoluteExpression(CurrValue))
3233 return true;
3234
3235 Values.push_back((uint8_t)CurrValue);
3236 }
3237
3238 getStreamer().EmitCFIEscape(Values);
3239 return false;
3240}
3241
Rafael Espindola16d7d432012-01-23 21:51:52 +00003242/// ParseDirectiveCFISignalFrame
3243/// ::= .cfi_signal_frame
3244bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3245 SMLoc DirectiveLoc) {
3246 if (getLexer().isNot(AsmToken::EndOfStatement))
3247 return Error(getLexer().getLoc(),
3248 "unexpected token in '" + Directive + "' directive");
3249
3250 getStreamer().EmitCFISignalFrame();
3251
3252 return false;
3253}
3254
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003255/// ParseDirectiveCFIUndefined
3256/// ::= .cfi_undefined register
3257bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3258 SMLoc DirectiveLoc) {
3259 int64_t Register = 0;
3260
3261 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3262 return true;
3263
3264 getStreamer().EmitCFIUndefined(Register);
3265
3266 return false;
3267}
3268
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003269/// ParseDirectiveCFIRegister
3270/// ::= .cfi_register register, register
3271bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3272 SMLoc DirectiveLoc) {
3273 int64_t Register1 = 0;
3274
3275 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3276 return true;
3277
3278 if (getLexer().isNot(AsmToken::Comma))
3279 return TokError("unexpected token in directive");
3280 Lex();
3281
3282 int64_t Register2 = 0;
3283
3284 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3285 return true;
3286
3287 getStreamer().EmitCFIRegister(Register1, Register2);
3288
3289 return false;
3290}
3291
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003292/// ParseDirectiveMacrosOnOff
3293/// ::= .macros_on
3294/// ::= .macros_off
3295bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3296 SMLoc DirectiveLoc) {
3297 if (getLexer().isNot(AsmToken::EndOfStatement))
3298 return Error(getLexer().getLoc(),
3299 "unexpected token in '" + Directive + "' directive");
3300
3301 getParser().MacrosEnabled = Directive == ".macros_on";
3302
3303 return false;
3304}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003305
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003306/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003307/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003308bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3309 SMLoc DirectiveLoc) {
3310 StringRef Name;
3311 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003312 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003313
Rafael Espindola8a403d32012-08-08 14:51:03 +00003314 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003315 // Argument delimiter is initially unknown. It will be set by
3316 // ParseMacroArgument()
3317 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003318 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003319 for (;;) {
3320 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003321 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003322 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003323
3324 if (getLexer().is(AsmToken::Equal)) {
3325 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003326 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003327 return true;
3328 }
3329
Rafael Espindola65366442011-06-05 02:43:45 +00003330 Parameters.push_back(Parameter);
3331
Preston Gurd7b6f2032012-09-19 20:36:12 +00003332 if (getLexer().is(AsmToken::Comma))
3333 Lex();
3334 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003335 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003336 }
3337 }
3338
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003339 // Eat the end of statement.
3340 Lex();
3341
3342 AsmToken EndToken, StartToken = getTok();
3343
3344 // Lex the macro definition.
3345 for (;;) {
3346 // Check whether we have reached the end of the file.
3347 if (getLexer().is(AsmToken::Eof))
3348 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3349
3350 // Otherwise, check whether we have reach the .endmacro.
3351 if (getLexer().is(AsmToken::Identifier) &&
3352 (getTok().getIdentifier() == ".endm" ||
3353 getTok().getIdentifier() == ".endmacro")) {
3354 EndToken = getTok();
3355 Lex();
3356 if (getLexer().isNot(AsmToken::EndOfStatement))
3357 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3358 "' directive");
3359 break;
3360 }
3361
3362 // Otherwise, scan til the end of the statement.
3363 getParser().EatToEndOfStatement();
3364 }
3365
3366 if (getParser().MacroMap.lookup(Name)) {
3367 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3368 }
3369
3370 const char *BodyStart = StartToken.getLoc().getPointer();
3371 const char *BodyEnd = EndToken.getLoc().getPointer();
3372 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003373 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003374 return false;
3375}
3376
3377/// ParseDirectiveEndMacro
3378/// ::= .endm
3379/// ::= .endmacro
3380bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003381 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003382 if (getLexer().isNot(AsmToken::EndOfStatement))
3383 return TokError("unexpected token in '" + Directive + "' directive");
3384
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003385 // If we are inside a macro instantiation, terminate the current
3386 // instantiation.
3387 if (!getParser().ActiveMacros.empty()) {
3388 getParser().HandleMacroExit();
3389 return false;
3390 }
3391
3392 // Otherwise, this .endmacro is a stray entry in the file; well formed
3393 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003394 return TokError("unexpected '" + Directive + "' in file, "
3395 "no current macro definition");
3396}
3397
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003398/// ParseDirectivePurgeMacro
3399/// ::= .purgem
3400bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3401 SMLoc DirectiveLoc) {
3402 StringRef Name;
3403 if (getParser().ParseIdentifier(Name))
3404 return TokError("expected identifier in '.purgem' directive");
3405
3406 if (getLexer().isNot(AsmToken::EndOfStatement))
3407 return TokError("unexpected token in '.purgem' directive");
3408
3409 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3410 if (I == getParser().MacroMap.end())
3411 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3412
3413 // Undefine the macro.
3414 delete I->getValue();
3415 getParser().MacroMap.erase(I);
3416 return false;
3417}
3418
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003419bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003420 getParser().CheckForValidSection();
3421
3422 const MCExpr *Value;
3423
3424 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003425 return true;
3426
3427 if (getLexer().isNot(AsmToken::EndOfStatement))
3428 return TokError("unexpected token in directive");
3429
3430 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003431 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003432 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003433 getStreamer().EmitULEB128Value(Value);
3434
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003435 return false;
3436}
3437
Rafael Espindola761cb062012-06-03 23:57:14 +00003438Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003439 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003440
Rafael Espindola761cb062012-06-03 23:57:14 +00003441 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003442 for (;;) {
3443 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003444 if (getLexer().is(AsmToken::Eof)) {
3445 Error(DirectiveLoc, "no matching '.endr' in definition");
3446 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003447 }
3448
Rafael Espindola761cb062012-06-03 23:57:14 +00003449 if (Lexer.is(AsmToken::Identifier) &&
3450 (getTok().getIdentifier() == ".rept")) {
3451 ++NestLevel;
3452 }
3453
3454 // Otherwise, check whether we have reached the .endr.
3455 if (Lexer.is(AsmToken::Identifier) &&
3456 getTok().getIdentifier() == ".endr") {
3457 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003458 EndToken = getTok();
3459 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003460 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3461 TokError("unexpected token in '.endr' directive");
3462 return 0;
3463 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003464 break;
3465 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003466 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003467 }
3468
Rafael Espindola761cb062012-06-03 23:57:14 +00003469 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003470 EatToEndOfStatement();
3471 }
3472
3473 const char *BodyStart = StartToken.getLoc().getPointer();
3474 const char *BodyEnd = EndToken.getLoc().getPointer();
3475 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3476
Rafael Espindola761cb062012-06-03 23:57:14 +00003477 // We Are Anonymous.
3478 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003479 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003480 return new Macro(Name, Body, Parameters);
3481}
3482
3483void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3484 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003485 OS << ".endr\n";
3486
3487 MemoryBuffer *Instantiation =
3488 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3489
Rafael Espindola761cb062012-06-03 23:57:14 +00003490 // Create the macro instantiation object and add to the current macro
3491 // instantiation stack.
3492 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3493 getTok().getLoc(),
3494 Instantiation);
3495 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003496
Rafael Espindola761cb062012-06-03 23:57:14 +00003497 // Jump to the macro instantiation and prime the lexer.
3498 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3499 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3500 Lex();
3501}
3502
3503bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3504 int64_t Count;
3505 if (ParseAbsoluteExpression(Count))
3506 return TokError("unexpected token in '.rept' directive");
3507
3508 if (Count < 0)
3509 return TokError("Count is negative");
3510
3511 if (Lexer.isNot(AsmToken::EndOfStatement))
3512 return TokError("unexpected token in '.rept' directive");
3513
3514 // Eat the end of statement.
3515 Lex();
3516
3517 // Lex the rept definition.
3518 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3519 if (!M)
3520 return true;
3521
3522 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3523 // to hold the macro body with substitutions.
3524 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003525 MacroParameters Parameters;
3526 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003527 raw_svector_ostream OS(Buf);
3528 while (Count--) {
3529 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3530 return true;
3531 }
3532 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003533
3534 return false;
3535}
3536
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003537/// ParseDirectiveIrp
3538/// ::= .irp symbol,values
3539bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003540 MacroParameters Parameters;
3541 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003542
Preston Gurd6c9176a2012-09-19 20:29:04 +00003543 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003544 return TokError("expected identifier in '.irp' directive");
3545
3546 Parameters.push_back(Parameter);
3547
3548 if (Lexer.isNot(AsmToken::Comma))
3549 return TokError("expected comma in '.irp' directive");
3550
3551 Lex();
3552
Rafael Espindola8a403d32012-08-08 14:51:03 +00003553 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003554 if (ParseMacroArguments(0, A))
3555 return true;
3556
3557 // Eat the end of statement.
3558 Lex();
3559
3560 // Lex the irp definition.
3561 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3562 if (!M)
3563 return true;
3564
3565 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3566 // to hold the macro body with substitutions.
3567 SmallString<256> Buf;
3568 raw_svector_ostream OS(Buf);
3569
Rafael Espindola7996d042012-08-21 16:06:48 +00003570 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3571 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003572 Args.push_back(*i);
3573
3574 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3575 return true;
3576 }
3577
3578 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3579
3580 return false;
3581}
3582
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003583/// ParseDirectiveIrpc
3584/// ::= .irpc symbol,values
3585bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003586 MacroParameters Parameters;
3587 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003588
Preston Gurd6c9176a2012-09-19 20:29:04 +00003589 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003590 return TokError("expected identifier in '.irpc' directive");
3591
3592 Parameters.push_back(Parameter);
3593
3594 if (Lexer.isNot(AsmToken::Comma))
3595 return TokError("expected comma in '.irpc' directive");
3596
3597 Lex();
3598
Rafael Espindola8a403d32012-08-08 14:51:03 +00003599 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003600 if (ParseMacroArguments(0, A))
3601 return true;
3602
3603 if (A.size() != 1 || A.front().size() != 1)
3604 return TokError("unexpected token in '.irpc' directive");
3605
3606 // Eat the end of statement.
3607 Lex();
3608
3609 // Lex the irpc definition.
3610 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3611 if (!M)
3612 return true;
3613
3614 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3615 // to hold the macro body with substitutions.
3616 SmallString<256> Buf;
3617 raw_svector_ostream OS(Buf);
3618
3619 StringRef Values = A.front().front().getString();
3620 std::size_t I, End = Values.size();
3621 for (I = 0; I < End; ++I) {
3622 MacroArgument Arg;
3623 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3624
Rafael Espindola8a403d32012-08-08 14:51:03 +00003625 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003626 Args.push_back(Arg);
3627
3628 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3629 return true;
3630 }
3631
3632 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3633
3634 return false;
3635}
3636
Rafael Espindola761cb062012-06-03 23:57:14 +00003637bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3638 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003639 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003640
3641 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003642 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003643 assert(getLexer().is(AsmToken::EndOfStatement));
3644
Rafael Espindola761cb062012-06-03 23:57:14 +00003645 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003646 return false;
3647}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003648
Eli Friedman2128aae2012-10-22 23:58:19 +00003649bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3650 const MCExpr *Value;
3651 SMLoc ExprLoc = getLexer().getLoc();
3652 if (ParseExpression(Value))
3653 return true;
3654 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3655 if (!MCE)
3656 return Error(ExprLoc, "unexpected expression in _emit");
3657 uint64_t IntValue = MCE->getValue();
3658 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3659 return Error(ExprLoc, "literal value out of range for directive");
3660
3661 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3662 return false;
3663}
3664
Chad Rosierb1f8c132012-10-18 15:49:34 +00003665bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3666 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003667 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003668 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003669 SmallVectorImpl<std::string> &Clobbers,
3670 const MCInstrInfo *MII,
3671 const MCInstPrinter *IP,
3672 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003673 SmallVector<void *, 4> InputDecls;
3674 SmallVector<void *, 4> OutputDecls;
3675 SmallVector<bool, 4> InputDeclsOffsetOf;
3676 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003677 SmallVector<std::string, 4> InputConstraints;
3678 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003679 std::set<std::string> ClobberRegs;
3680
Chad Rosier4e472d22012-10-20 01:02:45 +00003681 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003682
3683 // Prime the lexer.
3684 Lex();
3685
3686 // While we have input, parse each statement.
3687 unsigned InputIdx = 0;
3688 unsigned OutputIdx = 0;
3689 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003690 ParseStatementInfo Info(&AsmStrRewrites);
3691 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003692 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003693
Eli Friedman2128aae2012-10-22 23:58:19 +00003694 if (Info.Opcode != ~0U) {
3695 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003696
3697 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003698 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3699 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003700
3701 // Immediate.
3702 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003703 if (Operand->needAsmRewrite())
3704 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3705 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003706 continue;
3707 }
3708
3709 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003710 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003711 unsigned NumDefs = Desc.getNumDefs();
3712 // Clobber.
3713 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3714 std::string Reg;
3715 raw_string_ostream OS(Reg);
3716 IP->printRegName(OS, Operand->getReg());
3717 ClobberRegs.insert(StringRef(OS.str()));
3718 }
3719 continue;
3720 }
3721
3722 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003723 unsigned Size;
3724 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3725 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003726 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003727 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003728 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003729 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003730 Operand->getStartLoc(),
3731 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003732 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003733 if (isOutput) {
3734 std::string Constraint = "=";
3735 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003736 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003737 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003738 Constraint += Operand->getConstraint().str();
3739 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003740 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003741 Operand->getStartLoc(),
3742 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003743 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003744 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003745 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003746 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003747 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003748 Operand->getStartLoc(),
3749 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003750 }
3751 }
3752 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003753 }
3754 }
3755
3756 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003757 NumOutputs = OutputDecls.size();
3758 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003759
3760 // Set the unique clobbers.
3761 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3762 E = ClobberRegs.end(); I != E; ++I)
3763 Clobbers.push_back(*I);
3764
3765 // Merge the various outputs and inputs. Output are expected first.
3766 if (NumOutputs || NumInputs) {
3767 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003768 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003769 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003770 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3771 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003772 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003773 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3774 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003775 }
3776 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003777 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3778 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003779 }
3780 }
3781
3782 // Build the IR assembly string.
3783 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003784 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003785 raw_string_ostream OS(AsmStringIR);
3786 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003787 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003788 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3789 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003790
Chad Rosier4e472d22012-10-20 01:02:45 +00003791 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003792
3793 // Emit everything up to the immediate/expression. If the previous rewrite
3794 // was a size directive, then this has already been done.
3795 if (PrevKind != AOK_SizeDirective)
3796 OS << StringRef(Start, Loc - Start);
3797 PrevKind = Kind;
3798
Chad Rosier5a719fc2012-10-23 17:43:43 +00003799 // Skip the original expression.
3800 if (Kind == AOK_Skip) {
3801 Start = Loc + (*I).Len;
3802 continue;
3803 }
3804
Chad Rosierb1f8c132012-10-18 15:49:34 +00003805 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003806 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003807 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003808 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003809 OS << Twine("$$");
3810 OS << (*I).Val;
3811 break;
3812 case AOK_ImmPrefix:
3813 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003814 break;
3815 case AOK_Input:
3816 OS << '$';
3817 OS << InputIdx++;
3818 break;
3819 case AOK_Output:
3820 OS << '$';
3821 OS << OutputIdx++;
3822 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003823 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003824 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003825 default: break;
3826 case 8: OS << "byte ptr "; break;
3827 case 16: OS << "word ptr "; break;
3828 case 32: OS << "dword ptr "; break;
3829 case 64: OS << "qword ptr "; break;
3830 case 80: OS << "xword ptr "; break;
3831 case 128: OS << "xmmword ptr "; break;
3832 case 256: OS << "ymmword ptr "; break;
3833 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003834 break;
3835 case AOK_Emit:
3836 OS << ".byte";
3837 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003838 case AOK_DotOperator:
3839 OS << (*I).Val;
3840 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003841 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003842
Chad Rosierb1f8c132012-10-18 15:49:34 +00003843 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003844 if (Kind != AOK_SizeDirective)
3845 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003846 }
3847
3848 // Emit the remainder of the asm string.
3849 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3850 if (Start != AsmEnd)
3851 OS << StringRef(Start, AsmEnd - Start);
3852
3853 AsmString = OS.str();
3854 return false;
3855}
3856
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003857/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003858MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003859 MCContext &C, MCStreamer &Out,
3860 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003861 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003862}