blob: 6f2e85e55335b764f42c74dd5683525b47ff3b37 [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 Espindola1fdfbc42010-11-16 18:34:07 +0000399
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000400 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000401 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
402 ".macros_on");
403 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
404 ".macros_off");
405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
407 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000408 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000409
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
411 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000412 }
413
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000414 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
415
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000416 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000419 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000420 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000421 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000423 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000424 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000425 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000426 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
427 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000428 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000429 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000430 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
431 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000432 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000433 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000434 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000435 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000436
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000437 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000438 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
439 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000440 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000441
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000442 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000443};
444
445}
446
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000447namespace llvm {
448
449extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000450extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000451extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000452
453}
454
Chris Lattneraaec2052010-01-19 19:46:13 +0000455enum { DEFAULT_ADDRSPACE = 0 };
456
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000457AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000458 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000459 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000460 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000461 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000462 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000463 // Save the old handler.
464 SavedDiagHandler = SrcMgr.getDiagHandler();
465 SavedDiagContext = SrcMgr.getDiagContext();
466 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000467 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000468 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000469
470 // Initialize the generic parser.
471 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000472
473 // Initialize the platform / file format parser.
474 //
475 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
476 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000477 if (_MAI.hasMicrosoftFastStdCallMangling()) {
478 PlatformParser = createCOFFAsmParser();
479 PlatformParser->Initialize(*this);
480 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000481 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000482 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000483 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000484 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000485 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000486 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000487 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000488}
489
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000490AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000491 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
492
493 // Destroy any macros.
494 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
495 ie = MacroMap.end(); it != ie; ++it)
496 delete it->getValue();
497
Daniel Dunbare4749702010-07-12 18:12:02 +0000498 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000499 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000500}
501
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000502void AsmParser::PrintMacroInstantiations() {
503 // Print the active macro instantiation stack.
504 for (std::vector<MacroInstantiation*>::const_reverse_iterator
505 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000506 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
507 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000508}
509
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000510bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000511 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000512 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000513 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000514 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000515 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000516}
517
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000518bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000519 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000520 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000521 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000522 return true;
523}
524
Sean Callananfd0b0282010-01-21 00:19:58 +0000525bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000526 std::string IncludedFile;
527 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000528 if (NewBuf == -1)
529 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000530
Sean Callananfd0b0282010-01-21 00:19:58 +0000531 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000532
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535 return false;
536}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000537
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000538/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000539/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000540/// returns true on failure.
541bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
542 std::string IncludedFile;
543 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
544 if (NewBuf == -1)
545 return true;
546
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000547 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000548 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
549 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000550 return false;
551}
552
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000553void AsmParser::JumpToLoc(SMLoc Loc) {
554 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
555 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
556}
557
Sean Callananfd0b0282010-01-21 00:19:58 +0000558const AsmToken &AsmParser::Lex() {
559 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000560
Sean Callananfd0b0282010-01-21 00:19:58 +0000561 if (tok->is(AsmToken::Eof)) {
562 // If this is the end of an included file, pop the parent file off the
563 // include stack.
564 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
565 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000566 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000567 tok = &Lexer.Lex();
568 }
569 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000570
Sean Callananfd0b0282010-01-21 00:19:58 +0000571 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000572 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000573
Sean Callananfd0b0282010-01-21 00:19:58 +0000574 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000575}
576
Chris Lattner79180e22010-04-05 23:15:42 +0000577bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000578 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000579 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000580 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000581
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000582 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000583 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000584
585 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000586 AsmCond StartingCondState = TheCondState;
587
Kevin Enderby613b7572011-11-01 22:27:22 +0000588 // If we are generating dwarf for assembly source files save the initial text
589 // section and generate a .file directive.
590 if (getContext().getGenDwarfForAssembly()) {
591 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000592 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
593 getStreamer().EmitLabel(SectionStartSym);
594 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000595 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
596 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
597 }
598
Chris Lattnerb717fb02009-07-02 21:53:43 +0000599 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000600 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000601 ParseStatementInfo Info;
602 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000603
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000604 // We had an error, validate that one was emitted and recover by skipping to
605 // the next line.
606 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000607 EatToEndOfStatement();
608 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000609
610 if (TheCondState.TheCond != StartingCondState.TheCond ||
611 TheCondState.Ignore != StartingCondState.Ignore)
612 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000613
614 // Check to see there are no empty DwarfFile slots.
615 const std::vector<MCDwarfFile *> &MCDwarfFiles =
616 getContext().getMCDwarfFiles();
617 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000618 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000619 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000620 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000621
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000622 // Check to see that all assembler local symbols were actually defined.
623 // Targets that don't do subsections via symbols may not want this, though,
624 // so conservatively exclude them. Only do this if we're finalizing, though,
625 // as otherwise we won't necessarilly have seen everything yet.
626 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
627 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
628 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
629 e = Symbols.end();
630 i != e; ++i) {
631 MCSymbol *Sym = i->getValue();
632 // Variable symbols may not be marked as defined, so check those
633 // explicitly. If we know it's a variable, we have a definition for
634 // the purposes of this check.
635 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
636 // FIXME: We would really like to refer back to where the symbol was
637 // first referenced for a source location. We need to add something
638 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000639 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
640 "assembler local symbol '" + Sym->getName() +
641 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000642 }
643 }
644
645
Chris Lattner79180e22010-04-05 23:15:42 +0000646 // Finalize the output stream if there are no errors and if the client wants
647 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000648 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000649 Out.Finish();
650
Chris Lattnerb717fb02009-07-02 21:53:43 +0000651 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000652}
653
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000654void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000655 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000656 TokError("expected section directive before assembly directive");
657 Out.SwitchSection(Ctx.getMachOSection(
658 "__TEXT", "__text",
659 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
660 0, SectionKind::getText()));
661 }
662}
663
Chris Lattner2cf5f142009-06-22 01:29:09 +0000664/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
665void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000666 while (Lexer.isNot(AsmToken::EndOfStatement) &&
667 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000668 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000669
Chris Lattner2cf5f142009-06-22 01:29:09 +0000670 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000671 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000672 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000673}
674
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000675StringRef AsmParser::ParseStringToEndOfStatement() {
676 const char *Start = getTok().getLoc().getPointer();
677
678 while (Lexer.isNot(AsmToken::EndOfStatement) &&
679 Lexer.isNot(AsmToken::Eof))
680 Lex();
681
682 const char *End = getTok().getLoc().getPointer();
683 return StringRef(Start, End - Start);
684}
Chris Lattnerc4193832009-06-22 05:51:26 +0000685
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000686StringRef AsmParser::ParseStringToComma() {
687 const char *Start = getTok().getLoc().getPointer();
688
689 while (Lexer.isNot(AsmToken::EndOfStatement) &&
690 Lexer.isNot(AsmToken::Comma) &&
691 Lexer.isNot(AsmToken::Eof))
692 Lex();
693
694 const char *End = getTok().getLoc().getPointer();
695 return StringRef(Start, End - Start);
696}
697
Chris Lattner74ec1a32009-06-22 06:32:03 +0000698/// ParseParenExpr - Parse a paren expression and return it.
699/// NOTE: This assumes the leading '(' has already been consumed.
700///
701/// parenexpr ::= expr)
702///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000703bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000704 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000705 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000706 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000707 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000708 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000709 return false;
710}
Chris Lattnerc4193832009-06-22 05:51:26 +0000711
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000712/// ParseBracketExpr - Parse a bracket expression and return it.
713/// NOTE: This assumes the leading '[' has already been consumed.
714///
715/// bracketexpr ::= expr]
716///
717bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
718 if (ParseExpression(Res)) return true;
719 if (Lexer.isNot(AsmToken::RBrac))
720 return TokError("expected ']' in brackets expression");
721 EndLoc = Lexer.getLoc();
722 Lex();
723 return false;
724}
725
Chris Lattner74ec1a32009-06-22 06:32:03 +0000726/// ParsePrimaryExpr - Parse a primary expression and return it.
727/// primaryexpr ::= (parenexpr
728/// primaryexpr ::= symbol
729/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000730/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000731/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000732bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000733 switch (Lexer.getKind()) {
734 default:
735 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000736 // If we have an error assume that we've already handled it.
737 case AsmToken::Error:
738 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000739 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000740 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000741 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000742 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000743 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000744 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000745 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000746 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000747 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000748 EndLoc = Lexer.getLoc();
749
750 StringRef Identifier;
751 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000752 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000753
Daniel Dunbarfffff912009-10-16 01:34:54 +0000754 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000755 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000756 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000757
758 // Lookup the symbol variant if used.
759 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000760 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000761 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000762 if (Variant == MCSymbolRefExpr::VK_Invalid) {
763 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000764 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000765 }
766 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000767
Daniel Dunbarfffff912009-10-16 01:34:54 +0000768 // If this is an absolute variable reference, substitute it now to preserve
769 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000770 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000771 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000772 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000773
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000774 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 return false;
776 }
777
778 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000779 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000780 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000781 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000782 case AsmToken::Integer: {
783 SMLoc Loc = getTok().getLoc();
784 int64_t IntVal = getTok().getIntVal();
785 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000786 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000787 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000788 // Look for 'b' or 'f' following an Integer as a directional label
789 if (Lexer.getKind() == AsmToken::Identifier) {
790 StringRef IDVal = getTok().getString();
791 if (IDVal == "f" || IDVal == "b"){
792 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
793 IDVal == "f" ? 1 : 0);
794 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
795 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000796 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000797 return Error(Loc, "invalid reference to undefined symbol");
798 EndLoc = Lexer.getLoc();
799 Lex(); // Eat identifier.
800 }
801 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000802 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000803 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000804 case AsmToken::Real: {
805 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000806 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000807 Res = MCConstantExpr::Create(IntVal, getContext());
808 Lex(); // Eat token.
809 return false;
810 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000811 case AsmToken::Dot: {
812 // This is a '.' reference, which references the current PC. Emit a
813 // temporary label to the streamer and refer to it.
814 MCSymbol *Sym = Ctx.CreateTempSymbol();
815 Out.EmitLabel(Sym);
816 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
817 EndLoc = Lexer.getLoc();
818 Lex(); // Eat identifier.
819 return false;
820 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000821 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000822 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000823 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000824 case AsmToken::LBrac:
825 if (!PlatformParser->HasBracketExpressions())
826 return TokError("brackets expression not supported on this target");
827 Lex(); // Eat the '['.
828 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000829 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000830 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000831 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000832 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000833 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000834 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000835 case AsmToken::Plus:
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::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000840 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000841 case AsmToken::Tilde:
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::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000846 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000847 }
848}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000849
Chris Lattnerb4307b32010-01-15 19:28:38 +0000850bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000851 SMLoc EndLoc;
852 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000853}
854
Daniel Dunbarcceba832010-09-17 02:47:07 +0000855const MCExpr *
856AsmParser::ApplyModifierToExpr(const MCExpr *E,
857 MCSymbolRefExpr::VariantKind Variant) {
858 // Recurse over the given expression, rebuilding it to apply the given variant
859 // if there is exactly one symbol.
860 switch (E->getKind()) {
861 case MCExpr::Target:
862 case MCExpr::Constant:
863 return 0;
864
865 case MCExpr::SymbolRef: {
866 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
867
868 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
869 TokError("invalid variant on expression '" +
870 getTok().getIdentifier() + "' (already modified)");
871 return E;
872 }
873
874 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
875 }
876
877 case MCExpr::Unary: {
878 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
879 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
880 if (!Sub)
881 return 0;
882 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
883 }
884
885 case MCExpr::Binary: {
886 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
887 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
888 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
889
890 if (!LHS && !RHS)
891 return 0;
892
893 if (!LHS) LHS = BE->getLHS();
894 if (!RHS) RHS = BE->getRHS();
895
896 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
897 }
898 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000899
Craig Topper85814382012-02-07 05:05:23 +0000900 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000901}
902
Chris Lattner74ec1a32009-06-22 06:32:03 +0000903/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000904///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000905/// expr ::= expr &&,|| expr -> lowest.
906/// expr ::= expr |,^,&,! expr
907/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
908/// expr ::= expr <<,>> expr
909/// expr ::= expr +,- expr
910/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000911/// expr ::= primaryexpr
912///
Chris Lattner54482b42010-01-15 19:39:23 +0000913bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000914 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000915 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000916 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
917 return true;
918
Daniel Dunbarcceba832010-09-17 02:47:07 +0000919 // As a special case, we support 'a op b @ modifier' by rewriting the
920 // expression to include the modifier. This is inefficient, but in general we
921 // expect users to use 'a@modifier op b'.
922 if (Lexer.getKind() == AsmToken::At) {
923 Lex();
924
925 if (Lexer.isNot(AsmToken::Identifier))
926 return TokError("unexpected symbol modifier following '@'");
927
928 MCSymbolRefExpr::VariantKind Variant =
929 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
930 if (Variant == MCSymbolRefExpr::VK_Invalid)
931 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
932
933 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
934 if (!ModifiedRes) {
935 return TokError("invalid modifier '" + getTok().getIdentifier() +
936 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000937 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000938
Daniel Dunbarcceba832010-09-17 02:47:07 +0000939 Res = ModifiedRes;
940 Lex();
941 }
942
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000943 // Try to constant fold it up front, if possible.
944 int64_t Value;
945 if (Res->EvaluateAsAbsolute(Value))
946 Res = MCConstantExpr::Create(Value, getContext());
947
948 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000949}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000950
Chris Lattnerb4307b32010-01-15 19:28:38 +0000951bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000952 Res = 0;
953 return ParseParenExpr(Res, EndLoc) ||
954 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000955}
956
Daniel Dunbar475839e2009-06-29 20:37:27 +0000957bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000958 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000959
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000960 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000961 if (ParseExpression(Expr))
962 return true;
963
Daniel Dunbare00b0112009-10-16 01:57:52 +0000964 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000965 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000966
967 return false;
968}
969
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000970static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000971 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000972 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000973 default:
974 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000975
Jim Grosbachfbe16812011-08-20 16:24:13 +0000976 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000977 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000978 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000979 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000980 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000981 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000982 return 1;
983
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000984
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000985 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000986 //
987 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000988 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000989 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000990 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000991 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000992 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000993 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000994 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000995 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000996 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000997
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000998 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000999 case AsmToken::EqualEqual:
1000 Kind = MCBinaryExpr::EQ;
1001 return 3;
1002 case AsmToken::ExclaimEqual:
1003 case AsmToken::LessGreater:
1004 Kind = MCBinaryExpr::NE;
1005 return 3;
1006 case AsmToken::Less:
1007 Kind = MCBinaryExpr::LT;
1008 return 3;
1009 case AsmToken::LessEqual:
1010 Kind = MCBinaryExpr::LTE;
1011 return 3;
1012 case AsmToken::Greater:
1013 Kind = MCBinaryExpr::GT;
1014 return 3;
1015 case AsmToken::GreaterEqual:
1016 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001017 return 3;
1018
Jim Grosbachfbe16812011-08-20 16:24:13 +00001019 // Intermediate Precedence: <<, >>
1020 case AsmToken::LessLess:
1021 Kind = MCBinaryExpr::Shl;
1022 return 4;
1023 case AsmToken::GreaterGreater:
1024 Kind = MCBinaryExpr::Shr;
1025 return 4;
1026
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001027 // High Intermediate Precedence: +, -
1028 case AsmToken::Plus:
1029 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001030 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001031 case AsmToken::Minus:
1032 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001033 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001034
Jim Grosbachfbe16812011-08-20 16:24:13 +00001035 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001036 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001037 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001038 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001039 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001040 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001042 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001043 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001044 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001045 }
1046}
1047
1048
1049/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1050/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001051bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1052 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001053 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001054 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001055 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001056
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001057 // If the next token is lower precedence than we are allowed to eat, return
1058 // successfully with what we ate already.
1059 if (TokPrec < Precedence)
1060 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001061
Sean Callanan79ed1a82010-01-19 20:22:31 +00001062 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001063
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001064 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001065 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001066 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001067
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001068 // If BinOp binds less tightly with RHS than the operator after RHS, let
1069 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001070 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001071 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001072 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001073 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 }
1075
Daniel Dunbar475839e2009-06-29 20:37:27 +00001076 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001077 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001078 }
1079}
1080
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001081/// ParseStatement:
1082/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001083/// ::= Label* Directive ...Operands... EndOfStatement
1084/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001085bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001086 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001087 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001088 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001089 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001090 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001091
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001092 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001093 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001094 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001095 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001096 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001097 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001098 if (Lexer.is(AsmToken::Hash))
1099 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001100
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001101 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001102 if (Lexer.is(AsmToken::Integer)) {
1103 LocalLabelVal = getTok().getIntVal();
1104 if (LocalLabelVal < 0) {
1105 if (!TheCondState.Ignore)
1106 return TokError("unexpected token at start of statement");
1107 IDVal = "";
1108 }
1109 else {
1110 IDVal = getTok().getString();
1111 Lex(); // Consume the integer token to be used as an identifier token.
1112 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001113 if (!TheCondState.Ignore)
1114 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001115 }
1116 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001117
1118 } else if (Lexer.is(AsmToken::Dot)) {
1119 // Treat '.' as a valid identifier in this context.
1120 Lex();
1121 IDVal = ".";
1122
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001123 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001124 if (!TheCondState.Ignore)
1125 return TokError("unexpected token at start of statement");
1126 IDVal = "";
1127 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001128
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001129
Chris Lattner7834fac2010-04-17 18:14:27 +00001130 // Handle conditional assembly here before checking for skipping. We
1131 // have to do this so that .endif isn't skipped in a ".if 0" block for
1132 // example.
1133 if (IDVal == ".if")
1134 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001135 if (IDVal == ".ifb")
1136 return ParseDirectiveIfb(IDLoc, true);
1137 if (IDVal == ".ifnb")
1138 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001139 if (IDVal == ".ifc")
1140 return ParseDirectiveIfc(IDLoc, true);
1141 if (IDVal == ".ifnc")
1142 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001143 if (IDVal == ".ifdef")
1144 return ParseDirectiveIfdef(IDLoc, true);
1145 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1146 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001147 if (IDVal == ".elseif")
1148 return ParseDirectiveElseIf(IDLoc);
1149 if (IDVal == ".else")
1150 return ParseDirectiveElse(IDLoc);
1151 if (IDVal == ".endif")
1152 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001153
Chris Lattner7834fac2010-04-17 18:14:27 +00001154 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001155 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001156 EatToEndOfStatement();
1157 return false;
1158 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001159
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001160 // FIXME: Recurse on local labels?
1161
1162 // See what kind of statement we have.
1163 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001164 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001165 CheckForValidSection();
1166
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001167 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001168 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001169
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001170 // Diagnose attempt to use '.' as a label.
1171 if (IDVal == ".")
1172 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1173
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001174 // Diagnose attempt to use a variable as a label.
1175 //
1176 // FIXME: Diagnostics. Note the location of the definition as a label.
1177 // FIXME: This doesn't diagnose assignment to a symbol which has been
1178 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001179 MCSymbol *Sym;
1180 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001181 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001182 else
1183 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001184 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001185 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001186
Daniel Dunbar959fd882009-08-26 22:13:22 +00001187 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001188 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001189
Kevin Enderby94c2e852011-12-09 18:09:40 +00001190 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001191 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001192 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001193 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1194 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001195
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001196 // Consume any end of statement token, if present, to avoid spurious
1197 // AddBlankLine calls().
1198 if (Lexer.is(AsmToken::EndOfStatement)) {
1199 Lex();
1200 if (Lexer.is(AsmToken::Eof))
1201 return false;
1202 }
1203
Eli Friedman2128aae2012-10-22 23:58:19 +00001204 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001205 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001206
Daniel Dunbar3f872332009-07-28 16:08:33 +00001207 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001208 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001209 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001210
Nico Weber4c4c7322011-01-28 03:04:41 +00001211 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001212
1213 default: // Normal instruction or directive.
1214 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001215 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001216
1217 // If macros are enabled, check to see if this is a macro instantiation.
1218 if (MacrosEnabled)
1219 if (const Macro *M = MacroMap.lookup(IDVal))
1220 return HandleMacroEntry(IDVal, IDLoc, M);
1221
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001222 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001223 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001224
1225 // Target hook for parsing target specific directives.
1226 if (!getTargetParser().ParseDirective(ID))
1227 return false;
1228
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001229 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001230 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001231 return ParseDirectiveSet(IDVal, true);
1232 if (IDVal == ".equiv")
1233 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001234
Daniel Dunbara0d14262009-06-24 23:30:00 +00001235 // Data directives
1236
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001237 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001238 return ParseDirectiveAscii(IDVal, false);
1239 if (IDVal == ".asciz" || IDVal == ".string")
1240 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001241
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001242 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001243 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001244 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001245 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001246 if (IDVal == ".value")
1247 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001248 if (IDVal == ".2byte")
1249 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001250 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001251 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001252 if (IDVal == ".int")
1253 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001254 if (IDVal == ".4byte")
1255 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001257 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001258 if (IDVal == ".8byte")
1259 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001260 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001261 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1262 if (IDVal == ".double")
1263 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001264
Eli Friedman5d68ec22010-07-19 04:17:25 +00001265 if (IDVal == ".align") {
1266 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1267 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1268 }
1269 if (IDVal == ".align32") {
1270 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1271 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1272 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001273 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001274 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001275 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001276 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001277 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001278 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001279 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001280 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001281 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001282 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001283 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001284 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1285
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001286 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001287 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001288
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001290 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001291 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001292 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001293 if (IDVal == ".zero")
1294 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001295
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001296 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001297
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001298 if (IDVal == ".extern") {
1299 EatToEndOfStatement(); // .extern is the default, ignore it.
1300 return false;
1301 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001303 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001304 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001305 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001306 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001307 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001308 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001309 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001310 if (IDVal == ".symbol_resolver")
1311 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001312 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001313 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001314 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001315 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001316 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001317 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001318 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001319 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001320 if (IDVal == ".weak_def_can_be_hidden")
1321 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001322
Hans Wennborg5cc64912011-06-18 13:51:54 +00001323 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001324 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001325 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001326 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001327
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001328 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001329 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001330 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001331 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001332 if (IDVal == ".incbin")
1333 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001334
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001335 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001336 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001337
Rafael Espindola761cb062012-06-03 23:57:14 +00001338 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001339 if (IDVal == ".rept")
1340 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001341 if (IDVal == ".irp")
1342 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001343 if (IDVal == ".irpc")
1344 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001345 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001346 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001347
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001348 // Look up the handler in the handler table.
1349 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1350 DirectiveMap.lookup(IDVal);
1351 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001352 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001353
Kevin Enderby9c656452009-09-10 20:51:44 +00001354
Jim Grosbach686c0182012-05-01 18:38:27 +00001355 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001356 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001357
Eli Friedman2128aae2012-10-22 23:58:19 +00001358 // _emit
1359 if (ParsingInlineAsm && IDVal == "_emit")
1360 return ParseDirectiveEmit(IDLoc, Info);
1361
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001362 CheckForValidSection();
1363
Chris Lattnera7f13542010-05-19 23:34:33 +00001364 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001365 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001366 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001367 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001368
Chad Rosier6a020a72012-10-25 20:41:34 +00001369 ParseInstructionInfo IInfo(Info.AsmRewrites);
1370 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1371 IDLoc,Info.ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001372
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001373 // Dump the parsed representation, if requested.
1374 if (getShowParsedOperands()) {
1375 SmallString<256> Str;
1376 raw_svector_ostream OS(Str);
1377 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001378 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001379 if (i != 0)
1380 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001381 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001382 }
1383 OS << "]";
1384
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001385 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001386 }
1387
Kevin Enderby613b7572011-11-01 22:27:22 +00001388 // If we are generating dwarf for assembly source files and the current
1389 // section is the initial text section then generate a .loc directive for
1390 // the instruction.
1391 if (!HadError && getContext().getGenDwarfForAssembly() &&
1392 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001393
1394 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1395
1396 // If we previously parsed a cpp hash file line comment then make sure the
1397 // current Dwarf File is for the CppHashFilename if not then emit the
1398 // Dwarf File table for it and adjust the line number for the .loc.
1399 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1400 getContext().getMCDwarfFiles();
1401 if (CppHashFilename.size() != 0) {
1402 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1403 CppHashFilename)
1404 getStreamer().EmitDwarfFileDirective(
1405 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1406
Kevin Enderby32c1a822012-11-05 21:55:41 +00001407 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001408 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1409 }
1410
Kevin Enderby613b7572011-11-01 22:27:22 +00001411 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001412 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001413 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001414 StringRef());
1415 }
1416
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001417 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001418 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001419 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001420 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1421 Info.ParsedOperands,
1422 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001423 ParsingInlineAsm);
1424 }
Chris Lattner98986712010-01-14 22:21:20 +00001425
Chris Lattnercbf8a982010-09-11 16:18:25 +00001426 // Don't skip the rest of the line, the instruction parser is responsible for
1427 // that.
1428 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001429}
Chris Lattner9a023f72009-06-24 04:43:34 +00001430
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001431/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1432/// since they may not be able to be tokenized to get to the end of line token.
1433void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001434 if (!Lexer.is(AsmToken::EndOfStatement))
1435 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001436 // Eat EOL.
1437 Lex();
1438}
1439
1440/// ParseCppHashLineFilenameComment as this:
1441/// ::= # number "filename"
1442/// or just as a full line comment if it doesn't have a number and a string.
1443bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1444 Lex(); // Eat the hash token.
1445
1446 if (getLexer().isNot(AsmToken::Integer)) {
1447 // Consume the line since in cases it is not a well-formed line directive,
1448 // as if were simply a full line comment.
1449 EatToEndOfLine();
1450 return false;
1451 }
1452
1453 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001454 Lex();
1455
1456 if (getLexer().isNot(AsmToken::String)) {
1457 EatToEndOfLine();
1458 return false;
1459 }
1460
1461 StringRef Filename = getTok().getString();
1462 // Get rid of the enclosing quotes.
1463 Filename = Filename.substr(1, Filename.size()-2);
1464
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001465 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1466 CppHashLoc = L;
1467 CppHashFilename = Filename;
1468 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001469 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001470
1471 // Ignore any trailing characters, they're just comment.
1472 EatToEndOfLine();
1473 return false;
1474}
1475
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001476/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001477/// for the Filename and LineNo if any in the diagnostic.
1478void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1479 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1480 raw_ostream &OS = errs();
1481
1482 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1483 const SMLoc &DiagLoc = Diag.getLoc();
1484 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1485 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1486
1487 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1488 // before printing the message.
1489 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001490 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001491 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1492 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1493 }
1494
1495 // If we have not parsed a cpp hash line filename comment or the source
1496 // manager changed or buffer changed (like in a nested include) then just
1497 // print the normal diagnostic using its Filename and LineNo.
1498 if (!Parser->CppHashLineNumber ||
1499 &DiagSrcMgr != &Parser->SrcMgr ||
1500 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001501 if (Parser->SavedDiagHandler)
1502 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1503 else
1504 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001505 return;
1506 }
1507
1508 // Use the CppHashFilename and calculate a line number based on the
1509 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1510 // the diagnostic.
1511 const std::string Filename = Parser->CppHashFilename;
1512
1513 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1514 int CppHashLocLineNo =
1515 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1516 int LineNo = Parser->CppHashLineNumber - 1 +
1517 (DiagLocLineNo - CppHashLocLineNo);
1518
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001519 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1520 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001521 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001522 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001523
Benjamin Kramer04a04262011-10-16 10:48:29 +00001524 if (Parser->SavedDiagHandler)
1525 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1526 else
1527 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001528}
1529
Rafael Espindola799aacf2012-08-21 18:29:30 +00001530// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1531// difference being that that function accepts '@' as part of identifiers and
1532// we can't do that. AsmLexer.cpp should probably be changed to handle
1533// '@' as a special case when needed.
1534static bool isIdentifierChar(char c) {
1535 return isalnum(c) || c == '_' || c == '$' || c == '.';
1536}
1537
Rafael Espindola761cb062012-06-03 23:57:14 +00001538bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001539 const MacroParameters &Parameters,
1540 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001541 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001542 unsigned NParameters = Parameters.size();
1543 if (NParameters != 0 && NParameters != A.size())
1544 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001545
Preston Gurd7b6f2032012-09-19 20:36:12 +00001546 // A macro without parameters is handled differently on Darwin:
1547 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001548 while (!Body.empty()) {
1549 // Scan for the next substitution.
1550 std::size_t End = Body.size(), Pos = 0;
1551 for (; Pos != End; ++Pos) {
1552 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001553 if (!NParameters) {
1554 // This macro has no parameters, look for $0, $1, etc.
1555 if (Body[Pos] != '$' || Pos + 1 == End)
1556 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001557
Rafael Espindola65366442011-06-05 02:43:45 +00001558 char Next = Body[Pos + 1];
1559 if (Next == '$' || Next == 'n' || isdigit(Next))
1560 break;
1561 } else {
1562 // This macro has parameters, look for \foo, \bar, etc.
1563 if (Body[Pos] == '\\' && Pos + 1 != End)
1564 break;
1565 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001566 }
1567
1568 // Add the prefix.
1569 OS << Body.slice(0, Pos);
1570
1571 // Check if we reached the end.
1572 if (Pos == End)
1573 break;
1574
Rafael Espindola65366442011-06-05 02:43:45 +00001575 if (!NParameters) {
1576 switch (Body[Pos+1]) {
1577 // $$ => $
1578 case '$':
1579 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001580 break;
1581
Rafael Espindola65366442011-06-05 02:43:45 +00001582 // $n => number of arguments
1583 case 'n':
1584 OS << A.size();
1585 break;
1586
1587 // $[0-9] => argument
1588 default: {
1589 // Missing arguments are ignored.
1590 unsigned Index = Body[Pos+1] - '0';
1591 if (Index >= A.size())
1592 break;
1593
1594 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001595 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001596 ie = A[Index].end(); it != ie; ++it)
1597 OS << it->getString();
1598 break;
1599 }
1600 }
1601 Pos += 2;
1602 } else {
1603 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001604 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001605 ++I;
1606
1607 const char *Begin = Body.data() + Pos +1;
1608 StringRef Argument(Begin, I - (Pos +1));
1609 unsigned Index = 0;
1610 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001611 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001612 break;
1613
Preston Gurd7b6f2032012-09-19 20:36:12 +00001614 if (Index == NParameters) {
1615 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1616 Pos += 3;
1617 else {
1618 OS << '\\' << Argument;
1619 Pos = I;
1620 }
1621 } else {
1622 for (MacroArgument::const_iterator it = A[Index].begin(),
1623 ie = A[Index].end(); it != ie; ++it)
1624 if (it->getKind() == AsmToken::String)
1625 OS << it->getStringContents();
1626 else
1627 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001628
Preston Gurd7b6f2032012-09-19 20:36:12 +00001629 Pos += 1 + Argument.size();
1630 }
Rafael Espindola65366442011-06-05 02:43:45 +00001631 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001632 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001633 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001634 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001635
Rafael Espindola65366442011-06-05 02:43:45 +00001636 return false;
1637}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001638
Rafael Espindola65366442011-06-05 02:43:45 +00001639MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1640 MemoryBuffer *I)
1641 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1642{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001643}
1644
Preston Gurd7b6f2032012-09-19 20:36:12 +00001645static bool IsOperator(AsmToken::TokenKind kind)
1646{
1647 switch (kind)
1648 {
1649 default:
1650 return false;
1651 case AsmToken::Plus:
1652 case AsmToken::Minus:
1653 case AsmToken::Tilde:
1654 case AsmToken::Slash:
1655 case AsmToken::Star:
1656 case AsmToken::Dot:
1657 case AsmToken::Equal:
1658 case AsmToken::EqualEqual:
1659 case AsmToken::Pipe:
1660 case AsmToken::PipePipe:
1661 case AsmToken::Caret:
1662 case AsmToken::Amp:
1663 case AsmToken::AmpAmp:
1664 case AsmToken::Exclaim:
1665 case AsmToken::ExclaimEqual:
1666 case AsmToken::Percent:
1667 case AsmToken::Less:
1668 case AsmToken::LessEqual:
1669 case AsmToken::LessLess:
1670 case AsmToken::LessGreater:
1671 case AsmToken::Greater:
1672 case AsmToken::GreaterEqual:
1673 case AsmToken::GreaterGreater:
1674 return true;
1675 }
1676}
1677
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001678/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1679/// This is used for both default macro parameter values and the
1680/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001681bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1682 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001683 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001684 unsigned AddTokens = 0;
1685
1686 // gas accepts arguments separated by whitespace, except on Darwin
1687 if (!IsDarwin)
1688 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001689
1690 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001691 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1692 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001693 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001694 }
1695
1696 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1697 // Spaces and commas cannot be mixed to delimit parameters
1698 if (ArgumentDelimiter == AsmToken::Eof)
1699 ArgumentDelimiter = AsmToken::Comma;
1700 else if (ArgumentDelimiter != AsmToken::Comma) {
1701 Lexer.setSkipSpace(true);
1702 return TokError("expected ' ' for macro argument separator");
1703 }
1704 break;
1705 }
1706
1707 if (Lexer.is(AsmToken::Space)) {
1708 Lex(); // Eat spaces
1709
1710 // Spaces can delimit parameters, but could also be part an expression.
1711 // If the token after a space is an operator, add the token and the next
1712 // one into this argument
1713 if (ArgumentDelimiter == AsmToken::Space ||
1714 ArgumentDelimiter == AsmToken::Eof) {
1715 if (IsOperator(Lexer.getKind())) {
1716 // Check to see whether the token is used as an operator,
1717 // or part of an identifier
1718 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1719 if (*NextChar == ' ')
1720 AddTokens = 2;
1721 }
1722
1723 if (!AddTokens && ParenLevel == 0) {
1724 if (ArgumentDelimiter == AsmToken::Eof &&
1725 !IsOperator(Lexer.getKind()))
1726 ArgumentDelimiter = AsmToken::Space;
1727 break;
1728 }
1729 }
1730 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001731
1732 // HandleMacroEntry relies on not advancing the lexer here
1733 // to be able to fill in the remaining default parameter values
1734 if (Lexer.is(AsmToken::EndOfStatement))
1735 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001736
1737 // Adjust the current parentheses level.
1738 if (Lexer.is(AsmToken::LParen))
1739 ++ParenLevel;
1740 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1741 --ParenLevel;
1742
1743 // Append the token to the current argument list.
1744 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001745 if (AddTokens)
1746 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001747 Lex();
1748 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001749
1750 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001751 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001752 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001753 return false;
1754}
1755
1756// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001757bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001758 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001759 // Argument delimiter is initially unknown. It will be set by
1760 // ParseMacroArgument()
1761 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001762
1763 // Parse two kinds of macro invocations:
1764 // - macros defined without any parameters accept an arbitrary number of them
1765 // - macros defined with parameters accept at most that many of them
1766 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1767 ++Parameter) {
1768 MacroArgument MA;
1769
Preston Gurd7b6f2032012-09-19 20:36:12 +00001770 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001771 return true;
1772
Preston Gurd6c9176a2012-09-19 20:29:04 +00001773 if (!MA.empty() || !NParameters)
1774 A.push_back(MA);
1775 else if (NParameters) {
1776 if (!M->Parameters[Parameter].second.empty())
1777 A.push_back(M->Parameters[Parameter].second);
1778 }
Jim Grosbach97146442012-07-30 22:44:17 +00001779
Preston Gurd6c9176a2012-09-19 20:29:04 +00001780 // At the end of the statement, fill in remaining arguments that have
1781 // default values. If there aren't any, then the next argument is
1782 // required but missing
1783 if (Lexer.is(AsmToken::EndOfStatement)) {
1784 if (NParameters && Parameter < NParameters - 1) {
1785 if (M->Parameters[Parameter + 1].second.empty())
1786 return TokError("macro argument '" +
1787 Twine(M->Parameters[Parameter + 1].first) +
1788 "' is missing");
1789 else
1790 continue;
1791 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001792 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001793 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001794
1795 if (Lexer.is(AsmToken::Comma))
1796 Lex();
1797 }
1798 return TokError("Too many arguments");
1799}
1800
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001801bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1802 const Macro *M) {
1803 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1804 // this, although we should protect against infinite loops.
1805 if (ActiveMacros.size() == 20)
1806 return TokError("macros cannot be nested more than 20 levels deep");
1807
Rafael Espindola8a403d32012-08-08 14:51:03 +00001808 MacroArguments A;
1809 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001810 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001811
Jim Grosbach97146442012-07-30 22:44:17 +00001812 // Remove any trailing empty arguments. Do this after-the-fact as we have
1813 // to keep empty arguments in the middle of the list or positionality
1814 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001815 while (!A.empty() && A.back().empty())
1816 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001817
Rafael Espindola65366442011-06-05 02:43:45 +00001818 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1819 // to hold the macro body with substitutions.
1820 SmallString<256> Buf;
1821 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001822 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001823
Rafael Espindola8a403d32012-08-08 14:51:03 +00001824 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001825 return true;
1826
Rafael Espindola761cb062012-06-03 23:57:14 +00001827 // We include the .endmacro in the buffer as our queue to exit the macro
1828 // instantiation.
1829 OS << ".endmacro\n";
1830
Rafael Espindola65366442011-06-05 02:43:45 +00001831 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001832 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001833
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001834 // Create the macro instantiation object and add to the current macro
1835 // instantiation stack.
1836 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001837 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001838 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001839 ActiveMacros.push_back(MI);
1840
1841 // Jump to the macro instantiation and prime the lexer.
1842 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1843 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1844 Lex();
1845
1846 return false;
1847}
1848
1849void AsmParser::HandleMacroExit() {
1850 // Jump to the EndOfStatement we should return to, and consume it.
1851 JumpToLoc(ActiveMacros.back()->ExitLoc);
1852 Lex();
1853
1854 // Pop the instantiation entry.
1855 delete ActiveMacros.back();
1856 ActiveMacros.pop_back();
1857}
1858
Rafael Espindolae71cc862012-01-28 05:57:00 +00001859static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001860 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001861 case MCExpr::Binary: {
1862 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1863 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001864 break;
1865 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001866 case MCExpr::Target:
1867 case MCExpr::Constant:
1868 return false;
1869 case MCExpr::SymbolRef: {
1870 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001871 if (S.isVariable())
1872 return IsUsedIn(Sym, S.getVariableValue());
1873 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001874 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001875 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001876 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001877 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001878
1879 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001880}
1881
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001882bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1883 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001884 // FIXME: Use better location, we should use proper tokens.
1885 SMLoc EqualLoc = Lexer.getLoc();
1886
Daniel Dunbar821e3332009-08-31 08:09:28 +00001887 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001888 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001889 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001890
Rafael Espindolae71cc862012-01-28 05:57:00 +00001891 // Note: we don't count b as used in "a = b". This is to allow
1892 // a = b
1893 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001894
Daniel Dunbar3f872332009-07-28 16:08:33 +00001895 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001896 return TokError("unexpected token in assignment");
1897
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001898 // Error on assignment to '.'.
1899 if (Name == ".") {
1900 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1901 "(use '.space' or '.org').)"));
1902 }
1903
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001904 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001905 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001906
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001907 // Validate that the LHS is allowed to be a variable (either it has not been
1908 // used as a symbol, or it is an absolute symbol).
1909 MCSymbol *Sym = getContext().LookupSymbol(Name);
1910 if (Sym) {
1911 // Diagnose assignment to a label.
1912 //
1913 // FIXME: Diagnostics. Note the location of the definition as a label.
1914 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001915 if (IsUsedIn(Sym, Value))
1916 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1917 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001918 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001919 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1920 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001921 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001922 return Error(EqualLoc, "redefinition of '" + Name + "'");
1923 else if (!Sym->isVariable())
1924 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001925 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001926 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1927 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001928
1929 // Don't count these checks as uses.
1930 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001931 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001932 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001933
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001934 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001935
1936 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001937 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001938 if (NoDeadStrip)
1939 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1940
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001941
1942 return false;
1943}
1944
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001945/// ParseIdentifier:
1946/// ::= identifier
1947/// ::= string
1948bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001949 // The assembler has relaxed rules for accepting identifiers, in particular we
1950 // allow things like '.globl $foo', which would normally be separate
1951 // tokens. At this level, we have already lexed so we cannot (currently)
1952 // handle this as a context dependent token, instead we detect adjacent tokens
1953 // and return the combined identifier.
1954 if (Lexer.is(AsmToken::Dollar)) {
1955 SMLoc DollarLoc = getLexer().getLoc();
1956
1957 // Consume the dollar sign, and check for a following identifier.
1958 Lex();
1959 if (Lexer.isNot(AsmToken::Identifier))
1960 return true;
1961
1962 // We have a '$' followed by an identifier, make sure they are adjacent.
1963 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1964 return true;
1965
1966 // Construct the joined identifier and consume the token.
1967 Res = StringRef(DollarLoc.getPointer(),
1968 getTok().getIdentifier().size() + 1);
1969 Lex();
1970 return false;
1971 }
1972
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001973 if (Lexer.isNot(AsmToken::Identifier) &&
1974 Lexer.isNot(AsmToken::String))
1975 return true;
1976
Sean Callanan18b83232010-01-19 21:44:56 +00001977 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001978
Sean Callanan79ed1a82010-01-19 20:22:31 +00001979 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001980
1981 return false;
1982}
1983
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001984/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001985/// ::= .equ identifier ',' expression
1986/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001987/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001988bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001989 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001990
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001991 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001992 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001993
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001994 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001995 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001996 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001997
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001998 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001999}
2000
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002001bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002002 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002003
2004 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002005 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002006 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2007 if (Str[i] != '\\') {
2008 Data += Str[i];
2009 continue;
2010 }
2011
2012 // Recognize escaped characters. Note that this escape semantics currently
2013 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2014 ++i;
2015 if (i == e)
2016 return TokError("unexpected backslash at end of string");
2017
2018 // Recognize octal sequences.
2019 if ((unsigned) (Str[i] - '0') <= 7) {
2020 // Consume up to three octal characters.
2021 unsigned Value = Str[i] - '0';
2022
2023 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2024 ++i;
2025 Value = Value * 8 + (Str[i] - '0');
2026
2027 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2028 ++i;
2029 Value = Value * 8 + (Str[i] - '0');
2030 }
2031 }
2032
2033 if (Value > 255)
2034 return TokError("invalid octal escape sequence (out of range)");
2035
2036 Data += (unsigned char) Value;
2037 continue;
2038 }
2039
2040 // Otherwise recognize individual escapes.
2041 switch (Str[i]) {
2042 default:
2043 // Just reject invalid escape sequences for now.
2044 return TokError("invalid escape sequence (unrecognized character)");
2045
2046 case 'b': Data += '\b'; break;
2047 case 'f': Data += '\f'; break;
2048 case 'n': Data += '\n'; break;
2049 case 'r': Data += '\r'; break;
2050 case 't': Data += '\t'; break;
2051 case '"': Data += '"'; break;
2052 case '\\': Data += '\\'; break;
2053 }
2054 }
2055
2056 return false;
2057}
2058
Daniel Dunbara0d14262009-06-24 23:30:00 +00002059/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002060/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2061bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002062 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002063 CheckForValidSection();
2064
Daniel Dunbara0d14262009-06-24 23:30:00 +00002065 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002066 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002067 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002068
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002069 std::string Data;
2070 if (ParseEscapedString(Data))
2071 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002072
2073 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002074 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002075 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2076
Sean Callanan79ed1a82010-01-19 20:22:31 +00002077 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002078
2079 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002080 break;
2081
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002082 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002083 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002084 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002085 }
2086 }
2087
Sean Callanan79ed1a82010-01-19 20:22:31 +00002088 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002089 return false;
2090}
2091
2092/// ParseDirectiveValue
2093/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2094bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002095 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002096 CheckForValidSection();
2097
Daniel Dunbara0d14262009-06-24 23:30:00 +00002098 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002099 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002100 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002101 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002102 return true;
2103
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002104 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002105 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2106 assert(Size <= 8 && "Invalid size");
2107 uint64_t IntValue = MCE->getValue();
2108 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2109 return Error(ExprLoc, "literal value out of range for directive");
2110 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2111 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002112 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002113
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002114 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002115 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002116
Daniel Dunbara0d14262009-06-24 23:30:00 +00002117 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002118 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002119 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002120 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002121 }
2122 }
2123
Sean Callanan79ed1a82010-01-19 20:22:31 +00002124 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002125 return false;
2126}
2127
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002128/// ParseDirectiveRealValue
2129/// ::= (.single | .double) [ expression (, expression)* ]
2130bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2131 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2132 CheckForValidSection();
2133
2134 for (;;) {
2135 // We don't truly support arithmetic on floating point expressions, so we
2136 // have to manually parse unary prefixes.
2137 bool IsNeg = false;
2138 if (getLexer().is(AsmToken::Minus)) {
2139 Lex();
2140 IsNeg = true;
2141 } else if (getLexer().is(AsmToken::Plus))
2142 Lex();
2143
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002144 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002145 getLexer().isNot(AsmToken::Real) &&
2146 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002147 return TokError("unexpected token in directive");
2148
2149 // Convert to an APFloat.
2150 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002151 StringRef IDVal = getTok().getString();
2152 if (getLexer().is(AsmToken::Identifier)) {
2153 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2154 Value = APFloat::getInf(Semantics);
2155 else if (!IDVal.compare_lower("nan"))
2156 Value = APFloat::getNaN(Semantics, false, ~0);
2157 else
2158 return TokError("invalid floating point literal");
2159 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002160 APFloat::opInvalidOp)
2161 return TokError("invalid floating point literal");
2162 if (IsNeg)
2163 Value.changeSign();
2164
2165 // Consume the numeric token.
2166 Lex();
2167
2168 // Emit the value as an integer.
2169 APInt AsInt = Value.bitcastToAPInt();
2170 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2171 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2172
2173 if (getLexer().is(AsmToken::EndOfStatement))
2174 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002175
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002176 if (getLexer().isNot(AsmToken::Comma))
2177 return TokError("unexpected token in directive");
2178 Lex();
2179 }
2180 }
2181
2182 Lex();
2183 return false;
2184}
2185
Daniel Dunbara0d14262009-06-24 23:30:00 +00002186/// ParseDirectiveSpace
2187/// ::= .space expression [ , expression ]
2188bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002189 CheckForValidSection();
2190
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002192 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002193 return true;
2194
2195 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002196 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2197 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002198 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002199 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002200
Daniel Dunbar475839e2009-06-29 20:37:27 +00002201 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002202 return true;
2203
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002204 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002205 return TokError("unexpected token in '.space' directive");
2206 }
2207
Sean Callanan79ed1a82010-01-19 20:22:31 +00002208 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002209
2210 if (NumBytes <= 0)
2211 return TokError("invalid number of bytes in '.space' directive");
2212
2213 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002214 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215
2216 return false;
2217}
2218
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002219/// ParseDirectiveZero
2220/// ::= .zero expression
2221bool AsmParser::ParseDirectiveZero() {
2222 CheckForValidSection();
2223
2224 int64_t NumBytes;
2225 if (ParseAbsoluteExpression(NumBytes))
2226 return true;
2227
Rafael Espindolae452b172010-10-05 19:42:57 +00002228 int64_t Val = 0;
2229 if (getLexer().is(AsmToken::Comma)) {
2230 Lex();
2231 if (ParseAbsoluteExpression(Val))
2232 return true;
2233 }
2234
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002235 if (getLexer().isNot(AsmToken::EndOfStatement))
2236 return TokError("unexpected token in '.zero' directive");
2237
2238 Lex();
2239
Rafael Espindolae452b172010-10-05 19:42:57 +00002240 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002241
2242 return false;
2243}
2244
Daniel Dunbara0d14262009-06-24 23:30:00 +00002245/// ParseDirectiveFill
2246/// ::= .fill expression , expression , expression
2247bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002248 CheckForValidSection();
2249
Daniel Dunbara0d14262009-06-24 23:30:00 +00002250 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002251 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002252 return true;
2253
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002254 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002255 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002256 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002257
Daniel Dunbara0d14262009-06-24 23:30:00 +00002258 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002259 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002260 return true;
2261
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002262 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002263 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002264 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002265
Daniel Dunbara0d14262009-06-24 23:30:00 +00002266 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002267 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002268 return true;
2269
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002270 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002271 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002272
Sean Callanan79ed1a82010-01-19 20:22:31 +00002273 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002275 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2276 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002277
2278 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002279 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002280
2281 return false;
2282}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002283
2284/// ParseDirectiveOrg
2285/// ::= .org expression [ , expression ]
2286bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002287 CheckForValidSection();
2288
Daniel Dunbar821e3332009-08-31 08:09:28 +00002289 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002290 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002291 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002292 return true;
2293
2294 // Parse optional fill expression.
2295 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002296 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2297 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002298 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002299 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002300
Daniel Dunbar475839e2009-06-29 20:37:27 +00002301 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002302 return true;
2303
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002304 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002305 return TokError("unexpected token in '.org' directive");
2306 }
2307
Sean Callanan79ed1a82010-01-19 20:22:31 +00002308 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002309
Jim Grosbachebd4c052012-01-27 00:37:08 +00002310 // Only limited forms of relocatable expressions are accepted here, it
2311 // has to be relative to the current section. The streamer will return
2312 // 'true' if the expression wasn't evaluatable.
2313 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2314 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002315
2316 return false;
2317}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002318
2319/// ParseDirectiveAlign
2320/// ::= {.align, ...} expression [ , expression [ , expression ]]
2321bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002322 CheckForValidSection();
2323
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002324 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002325 int64_t Alignment;
2326 if (ParseAbsoluteExpression(Alignment))
2327 return true;
2328
2329 SMLoc MaxBytesLoc;
2330 bool HasFillExpr = false;
2331 int64_t FillExpr = 0;
2332 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002333 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2334 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002335 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002336 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002337
2338 // The fill expression can be omitted while specifying a maximum number of
2339 // alignment bytes, e.g:
2340 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002341 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002342 HasFillExpr = true;
2343 if (ParseAbsoluteExpression(FillExpr))
2344 return true;
2345 }
2346
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002347 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2348 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002349 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002350 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002351
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002352 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002353 if (ParseAbsoluteExpression(MaxBytesToFill))
2354 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002355
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002356 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002357 return TokError("unexpected token in directive");
2358 }
2359 }
2360
Sean Callanan79ed1a82010-01-19 20:22:31 +00002361 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002362
Daniel Dunbar648ac512010-05-17 21:54:30 +00002363 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002364 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002365
2366 // Compute alignment in bytes.
2367 if (IsPow2) {
2368 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002369 if (Alignment >= 32) {
2370 Error(AlignmentLoc, "invalid alignment value");
2371 Alignment = 31;
2372 }
2373
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002374 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002375 }
2376
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002377 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002378 if (MaxBytesLoc.isValid()) {
2379 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002380 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2381 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002382 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002383 }
2384
2385 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002386 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2387 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002388 MaxBytesToFill = 0;
2389 }
2390 }
2391
Daniel Dunbar648ac512010-05-17 21:54:30 +00002392 // Check whether we should use optimal code alignment for this .align
2393 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002394 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002395 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2396 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002397 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002398 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002399 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002400 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2401 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002402 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002403
2404 return false;
2405}
2406
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002407/// ParseDirectiveSymbolAttribute
2408/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002409bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002410 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002411 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002412 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002413 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002414
2415 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002416 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002417
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002418 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002419
Jim Grosbach10ec6502011-09-15 17:56:49 +00002420 // Assembler local symbols don't make any sense here. Complain loudly.
2421 if (Sym->isTemporary())
2422 return Error(Loc, "non-local symbol required in directive");
2423
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002425
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002426 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002427 break;
2428
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002429 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002430 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002431 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002432 }
2433 }
2434
Sean Callanan79ed1a82010-01-19 20:22:31 +00002435 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002436 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002437}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002438
2439/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002440/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2441bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002442 CheckForValidSection();
2443
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002444 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002445 StringRef Name;
2446 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002447 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002448
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002449 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002450 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002451
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002452 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002453 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002454 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002455
2456 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002457 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002458 if (ParseAbsoluteExpression(Size))
2459 return true;
2460
2461 int64_t Pow2Alignment = 0;
2462 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002463 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002464 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002465 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002466 if (ParseAbsoluteExpression(Pow2Alignment))
2467 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002468
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002469 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2470 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002471 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2472
Chris Lattner258281d2010-01-19 06:22:22 +00002473 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002474 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2475 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002476 if (!isPowerOf2_64(Pow2Alignment))
2477 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2478 Pow2Alignment = Log2_64(Pow2Alignment);
2479 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002480 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002481
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002482 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002483 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002484
Sean Callanan79ed1a82010-01-19 20:22:31 +00002485 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002486
Chris Lattner1fc3d752009-07-09 17:25:12 +00002487 // NOTE: a size of zero for a .comm should create a undefined symbol
2488 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002489 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002490 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2491 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002492
Eric Christopherc260a3e2010-05-14 01:38:54 +00002493 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002494 // may internally end up wanting an alignment in bytes.
2495 // FIXME: Diagnose overflow.
2496 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002497 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2498 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002499
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002500 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002501 return Error(IDLoc, "invalid symbol redefinition");
2502
Chris Lattner1fc3d752009-07-09 17:25:12 +00002503 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002504 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002505 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002506 return false;
2507 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002508
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002509 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002510 return false;
2511}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002512
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002513/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002514/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002515bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002516 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002517 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002518
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002519 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002520 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002521 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002522
Sean Callanan79ed1a82010-01-19 20:22:31 +00002523 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002524
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002525 if (Str.empty())
2526 Error(Loc, ".abort detected. Assembly stopping.");
2527 else
2528 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002529 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002530
2531 return false;
2532}
Kevin Enderby71148242009-07-14 21:35:03 +00002533
Kevin Enderby1f049b22009-07-14 23:21:55 +00002534/// ParseDirectiveInclude
2535/// ::= .include "filename"
2536bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002537 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002538 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002539
Sean Callanan18b83232010-01-19 21:44:56 +00002540 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002541 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002542 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002543
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002544 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002545 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002546
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002547 // Strip the quotes.
2548 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002549
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002550 // Attempt to switch the lexer to the included file before consuming the end
2551 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002552 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002553 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002554 return true;
2555 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002556
2557 return false;
2558}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002559
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002560/// ParseDirectiveIncbin
2561/// ::= .incbin "filename"
2562bool AsmParser::ParseDirectiveIncbin() {
2563 if (getLexer().isNot(AsmToken::String))
2564 return TokError("expected string in '.incbin' directive");
2565
2566 std::string Filename = getTok().getString();
2567 SMLoc IncbinLoc = getLexer().getLoc();
2568 Lex();
2569
2570 if (getLexer().isNot(AsmToken::EndOfStatement))
2571 return TokError("unexpected token in '.incbin' directive");
2572
2573 // Strip the quotes.
2574 Filename = Filename.substr(1, Filename.size()-2);
2575
2576 // Attempt to process the included file.
2577 if (ProcessIncbinFile(Filename)) {
2578 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2579 return true;
2580 }
2581
2582 return false;
2583}
2584
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002585/// ParseDirectiveIf
2586/// ::= .if expression
2587bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002588 TheCondStack.push_back(TheCondState);
2589 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002590 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002591 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002592 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002593 int64_t ExprValue;
2594 if (ParseAbsoluteExpression(ExprValue))
2595 return true;
2596
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002597 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002598 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002599
Sean Callanan79ed1a82010-01-19 20:22:31 +00002600 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002601
2602 TheCondState.CondMet = ExprValue;
2603 TheCondState.Ignore = !TheCondState.CondMet;
2604 }
2605
2606 return false;
2607}
2608
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002609/// ParseDirectiveIfb
2610/// ::= .ifb string
2611bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2612 TheCondStack.push_back(TheCondState);
2613 TheCondState.TheCond = AsmCond::IfCond;
2614
Benjamin Kramer29739e72012-05-12 16:52:21 +00002615 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002616 EatToEndOfStatement();
2617 } else {
2618 StringRef Str = ParseStringToEndOfStatement();
2619
2620 if (getLexer().isNot(AsmToken::EndOfStatement))
2621 return TokError("unexpected token in '.ifb' directive");
2622
2623 Lex();
2624
2625 TheCondState.CondMet = ExpectBlank == Str.empty();
2626 TheCondState.Ignore = !TheCondState.CondMet;
2627 }
2628
2629 return false;
2630}
2631
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002632/// ParseDirectiveIfc
2633/// ::= .ifc string1, string2
2634bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2635 TheCondStack.push_back(TheCondState);
2636 TheCondState.TheCond = AsmCond::IfCond;
2637
Benjamin Kramer29739e72012-05-12 16:52:21 +00002638 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002639 EatToEndOfStatement();
2640 } else {
2641 StringRef Str1 = ParseStringToComma();
2642
2643 if (getLexer().isNot(AsmToken::Comma))
2644 return TokError("unexpected token in '.ifc' directive");
2645
2646 Lex();
2647
2648 StringRef Str2 = ParseStringToEndOfStatement();
2649
2650 if (getLexer().isNot(AsmToken::EndOfStatement))
2651 return TokError("unexpected token in '.ifc' directive");
2652
2653 Lex();
2654
2655 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2656 TheCondState.Ignore = !TheCondState.CondMet;
2657 }
2658
2659 return false;
2660}
2661
2662/// ParseDirectiveIfdef
2663/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002664bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2665 StringRef Name;
2666 TheCondStack.push_back(TheCondState);
2667 TheCondState.TheCond = AsmCond::IfCond;
2668
2669 if (TheCondState.Ignore) {
2670 EatToEndOfStatement();
2671 } else {
2672 if (ParseIdentifier(Name))
2673 return TokError("expected identifier after '.ifdef'");
2674
2675 Lex();
2676
2677 MCSymbol *Sym = getContext().LookupSymbol(Name);
2678
2679 if (expect_defined)
2680 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2681 else
2682 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2683 TheCondState.Ignore = !TheCondState.CondMet;
2684 }
2685
2686 return false;
2687}
2688
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002689/// ParseDirectiveElseIf
2690/// ::= .elseif expression
2691bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2692 if (TheCondState.TheCond != AsmCond::IfCond &&
2693 TheCondState.TheCond != AsmCond::ElseIfCond)
2694 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2695 " an .elseif");
2696 TheCondState.TheCond = AsmCond::ElseIfCond;
2697
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002698 bool LastIgnoreState = false;
2699 if (!TheCondStack.empty())
2700 LastIgnoreState = TheCondStack.back().Ignore;
2701 if (LastIgnoreState || TheCondState.CondMet) {
2702 TheCondState.Ignore = true;
2703 EatToEndOfStatement();
2704 }
2705 else {
2706 int64_t ExprValue;
2707 if (ParseAbsoluteExpression(ExprValue))
2708 return true;
2709
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002710 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002711 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002712
Sean Callanan79ed1a82010-01-19 20:22:31 +00002713 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002714 TheCondState.CondMet = ExprValue;
2715 TheCondState.Ignore = !TheCondState.CondMet;
2716 }
2717
2718 return false;
2719}
2720
2721/// ParseDirectiveElse
2722/// ::= .else
2723bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002724 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002725 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002726
Sean Callanan79ed1a82010-01-19 20:22:31 +00002727 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002728
2729 if (TheCondState.TheCond != AsmCond::IfCond &&
2730 TheCondState.TheCond != AsmCond::ElseIfCond)
2731 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2732 ".elseif");
2733 TheCondState.TheCond = AsmCond::ElseCond;
2734 bool LastIgnoreState = false;
2735 if (!TheCondStack.empty())
2736 LastIgnoreState = TheCondStack.back().Ignore;
2737 if (LastIgnoreState || TheCondState.CondMet)
2738 TheCondState.Ignore = true;
2739 else
2740 TheCondState.Ignore = false;
2741
2742 return false;
2743}
2744
2745/// ParseDirectiveEndIf
2746/// ::= .endif
2747bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002748 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002749 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002750
Sean Callanan79ed1a82010-01-19 20:22:31 +00002751 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002752
2753 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2754 TheCondStack.empty())
2755 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2756 ".else");
2757 if (!TheCondStack.empty()) {
2758 TheCondState = TheCondStack.back();
2759 TheCondStack.pop_back();
2760 }
2761
2762 return false;
2763}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002764
2765/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002766/// ::= .file [number] filename
2767/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002768bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002769 // FIXME: I'm not sure what this is.
2770 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002771 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002772 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002773 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002774 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002775
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002776 if (FileNumber < 1)
2777 return TokError("file number less than one");
2778 }
2779
Daniel Dunbareceec052010-07-12 17:45:27 +00002780 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002781 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002782
Nick Lewycky44d798d2011-10-17 23:05:28 +00002783 // Usually the directory and filename together, otherwise just the directory.
2784 StringRef Path = getTok().getString();
2785 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002786 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002787
Nick Lewycky44d798d2011-10-17 23:05:28 +00002788 StringRef Directory;
2789 StringRef Filename;
2790 if (getLexer().is(AsmToken::String)) {
2791 if (FileNumber == -1)
2792 return TokError("explicit path specified, but no file number");
2793 Filename = getTok().getString();
2794 Filename = Filename.substr(1, Filename.size()-2);
2795 Directory = Path;
2796 Lex();
2797 } else {
2798 Filename = Path;
2799 }
2800
Daniel Dunbareceec052010-07-12 17:45:27 +00002801 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002802 return TokError("unexpected token in '.file' directive");
2803
Chris Lattnerd32e8032010-01-25 19:02:58 +00002804 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002805 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002806 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002807 if (getContext().getGenDwarfForAssembly() == true)
2808 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2809 "used to generate dwarf debug info for assembly code");
2810
Nick Lewycky44d798d2011-10-17 23:05:28 +00002811 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002812 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002813 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002814
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002815 return false;
2816}
2817
2818/// ParseDirectiveLine
2819/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002820bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002821 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2822 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002823 return TokError("unexpected token in '.line' directive");
2824
Sean Callanan18b83232010-01-19 21:44:56 +00002825 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002826 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002827 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002828
2829 // FIXME: Do something with the .line.
2830 }
2831
Daniel Dunbareceec052010-07-12 17:45:27 +00002832 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002833 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002834
2835 return false;
2836}
2837
2838
2839/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002840/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002841/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2842/// The first number is a file number, must have been previously assigned with
2843/// a .file directive, the second number is the line number and optionally the
2844/// third number is a column position (zero if not specified). The remaining
2845/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002846bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002847
Daniel Dunbareceec052010-07-12 17:45:27 +00002848 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002849 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002850 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002851 if (FileNumber < 1)
2852 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002853 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002854 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002855 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002856
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002857 int64_t LineNumber = 0;
2858 if (getLexer().is(AsmToken::Integer)) {
2859 LineNumber = getTok().getIntVal();
2860 if (LineNumber < 1)
2861 return TokError("line number less than one in '.loc' directive");
2862 Lex();
2863 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002864
2865 int64_t ColumnPos = 0;
2866 if (getLexer().is(AsmToken::Integer)) {
2867 ColumnPos = getTok().getIntVal();
2868 if (ColumnPos < 0)
2869 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002870 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002871 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002872
Kevin Enderbyc0957932010-09-30 16:52:03 +00002873 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002874 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002875 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002876 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2877 for (;;) {
2878 if (getLexer().is(AsmToken::EndOfStatement))
2879 break;
2880
2881 StringRef Name;
2882 SMLoc Loc = getTok().getLoc();
2883 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002884 return TokError("unexpected token in '.loc' directive");
2885
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002886 if (Name == "basic_block")
2887 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2888 else if (Name == "prologue_end")
2889 Flags |= DWARF2_FLAG_PROLOGUE_END;
2890 else if (Name == "epilogue_begin")
2891 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2892 else if (Name == "is_stmt") {
2893 SMLoc Loc = getTok().getLoc();
2894 const MCExpr *Value;
2895 if (getParser().ParseExpression(Value))
2896 return true;
2897 // The expression must be the constant 0 or 1.
2898 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2899 int Value = MCE->getValue();
2900 if (Value == 0)
2901 Flags &= ~DWARF2_FLAG_IS_STMT;
2902 else if (Value == 1)
2903 Flags |= DWARF2_FLAG_IS_STMT;
2904 else
2905 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002906 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002907 else {
2908 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2909 }
2910 }
2911 else if (Name == "isa") {
2912 SMLoc Loc = getTok().getLoc();
2913 const MCExpr *Value;
2914 if (getParser().ParseExpression(Value))
2915 return true;
2916 // The expression must be a constant greater or equal to 0.
2917 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2918 int Value = MCE->getValue();
2919 if (Value < 0)
2920 return Error(Loc, "isa number less than zero");
2921 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002922 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002923 else {
2924 return Error(Loc, "isa number not a constant value");
2925 }
2926 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002927 else if (Name == "discriminator") {
2928 if (getParser().ParseAbsoluteExpression(Discriminator))
2929 return true;
2930 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002931 else {
2932 return Error(Loc, "unknown sub-directive in '.loc' directive");
2933 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002934
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002935 if (getLexer().is(AsmToken::EndOfStatement))
2936 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002937 }
2938 }
2939
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002940 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002941 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002942
2943 return false;
2944}
2945
Daniel Dunbar138abae2010-10-16 04:56:42 +00002946/// ParseDirectiveStabs
2947/// ::= .stabs string, number, number, number
2948bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2949 SMLoc DirectiveLoc) {
2950 return TokError("unsupported directive '" + Directive + "'");
2951}
2952
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002953/// ParseDirectiveCFISections
2954/// ::= .cfi_sections section [, section]
2955bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2956 SMLoc DirectiveLoc) {
2957 StringRef Name;
2958 bool EH = false;
2959 bool Debug = false;
2960
2961 if (getParser().ParseIdentifier(Name))
2962 return TokError("Expected an identifier");
2963
2964 if (Name == ".eh_frame")
2965 EH = true;
2966 else if (Name == ".debug_frame")
2967 Debug = true;
2968
2969 if (getLexer().is(AsmToken::Comma)) {
2970 Lex();
2971
2972 if (getParser().ParseIdentifier(Name))
2973 return TokError("Expected an identifier");
2974
2975 if (Name == ".eh_frame")
2976 EH = true;
2977 else if (Name == ".debug_frame")
2978 Debug = true;
2979 }
2980
2981 getStreamer().EmitCFISections(EH, Debug);
2982
2983 return false;
2984}
2985
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002986/// ParseDirectiveCFIStartProc
2987/// ::= .cfi_startproc
2988bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2989 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002990 getStreamer().EmitCFIStartProc();
2991 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002992}
2993
2994/// ParseDirectiveCFIEndProc
2995/// ::= .cfi_endproc
2996bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002997 getStreamer().EmitCFIEndProc();
2998 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002999}
3000
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003001/// ParseRegisterOrRegisterNumber - parse register name or number.
3002bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3003 SMLoc DirectiveLoc) {
3004 unsigned RegNo;
3005
Jim Grosbach6f888a82011-06-02 17:14:04 +00003006 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003007 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3008 DirectiveLoc))
3009 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003010 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003011 } else
3012 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003013
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003014 return false;
3015}
3016
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003017/// ParseDirectiveCFIDefCfa
3018/// ::= .cfi_def_cfa register, offset
3019bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3020 SMLoc DirectiveLoc) {
3021 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003022 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003023 return true;
3024
3025 if (getLexer().isNot(AsmToken::Comma))
3026 return TokError("unexpected token in directive");
3027 Lex();
3028
3029 int64_t Offset = 0;
3030 if (getParser().ParseAbsoluteExpression(Offset))
3031 return true;
3032
Rafael Espindola066c2f42011-04-12 23:59:07 +00003033 getStreamer().EmitCFIDefCfa(Register, Offset);
3034 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003035}
3036
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003037/// ParseDirectiveCFIDefCfaOffset
3038/// ::= .cfi_def_cfa_offset offset
3039bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3040 SMLoc DirectiveLoc) {
3041 int64_t Offset = 0;
3042 if (getParser().ParseAbsoluteExpression(Offset))
3043 return true;
3044
Rafael Espindola066c2f42011-04-12 23:59:07 +00003045 getStreamer().EmitCFIDefCfaOffset(Offset);
3046 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003047}
3048
3049/// ParseDirectiveCFIAdjustCfaOffset
3050/// ::= .cfi_adjust_cfa_offset adjustment
3051bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3052 SMLoc DirectiveLoc) {
3053 int64_t Adjustment = 0;
3054 if (getParser().ParseAbsoluteExpression(Adjustment))
3055 return true;
3056
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003057 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3058 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003059}
3060
3061/// ParseDirectiveCFIDefCfaRegister
3062/// ::= .cfi_def_cfa_register register
3063bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3064 SMLoc DirectiveLoc) {
3065 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003066 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003067 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003068
Rafael Espindola066c2f42011-04-12 23:59:07 +00003069 getStreamer().EmitCFIDefCfaRegister(Register);
3070 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003071}
3072
3073/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003074/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003075bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3076 int64_t Register = 0;
3077 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003078
3079 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003080 return true;
3081
3082 if (getLexer().isNot(AsmToken::Comma))
3083 return TokError("unexpected token in directive");
3084 Lex();
3085
3086 if (getParser().ParseAbsoluteExpression(Offset))
3087 return true;
3088
Rafael Espindola066c2f42011-04-12 23:59:07 +00003089 getStreamer().EmitCFIOffset(Register, Offset);
3090 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003091}
3092
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003093/// ParseDirectiveCFIRelOffset
3094/// ::= .cfi_rel_offset register, offset
3095bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3096 SMLoc DirectiveLoc) {
3097 int64_t Register = 0;
3098
3099 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3100 return true;
3101
3102 if (getLexer().isNot(AsmToken::Comma))
3103 return TokError("unexpected token in directive");
3104 Lex();
3105
3106 int64_t Offset = 0;
3107 if (getParser().ParseAbsoluteExpression(Offset))
3108 return true;
3109
Rafael Espindola25f492e2011-04-12 16:12:03 +00003110 getStreamer().EmitCFIRelOffset(Register, Offset);
3111 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003112}
3113
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003114static bool isValidEncoding(int64_t Encoding) {
3115 if (Encoding & ~0xff)
3116 return false;
3117
3118 if (Encoding == dwarf::DW_EH_PE_omit)
3119 return true;
3120
3121 const unsigned Format = Encoding & 0xf;
3122 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3123 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3124 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3125 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3126 return false;
3127
Rafael Espindolacaf11582010-12-29 04:31:26 +00003128 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003129 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003130 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003131 return false;
3132
3133 return true;
3134}
3135
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003136/// ParseDirectiveCFIPersonalityOrLsda
3137/// ::= .cfi_personality encoding, [symbol_name]
3138/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003139bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003140 SMLoc DirectiveLoc) {
3141 int64_t Encoding = 0;
3142 if (getParser().ParseAbsoluteExpression(Encoding))
3143 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003144 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003145 return false;
3146
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003147 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003148 return TokError("unsupported encoding.");
3149
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003150 if (getLexer().isNot(AsmToken::Comma))
3151 return TokError("unexpected token in directive");
3152 Lex();
3153
3154 StringRef Name;
3155 if (getParser().ParseIdentifier(Name))
3156 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003157
3158 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3159
3160 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003161 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003162 else {
3163 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003164 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003165 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003166 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003167}
3168
Rafael Espindolafe024d02010-12-28 18:36:23 +00003169/// ParseDirectiveCFIRememberState
3170/// ::= .cfi_remember_state
3171bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3172 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003173 getStreamer().EmitCFIRememberState();
3174 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003175}
3176
3177/// ParseDirectiveCFIRestoreState
3178/// ::= .cfi_remember_state
3179bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3180 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003181 getStreamer().EmitCFIRestoreState();
3182 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003183}
3184
Rafael Espindolac5754392011-04-12 15:31:05 +00003185/// ParseDirectiveCFISameValue
3186/// ::= .cfi_same_value register
3187bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3188 SMLoc DirectiveLoc) {
3189 int64_t Register = 0;
3190
3191 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3192 return true;
3193
3194 getStreamer().EmitCFISameValue(Register);
3195
3196 return false;
3197}
3198
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003199/// ParseDirectiveCFIRestore
3200/// ::= .cfi_restore register
3201bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003202 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003203 int64_t Register = 0;
3204 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3205 return true;
3206
3207 getStreamer().EmitCFIRestore(Register);
3208
3209 return false;
3210}
3211
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003212/// ParseDirectiveCFIEscape
3213/// ::= .cfi_escape expression[,...]
3214bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003215 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003216 std::string Values;
3217 int64_t CurrValue;
3218 if (getParser().ParseAbsoluteExpression(CurrValue))
3219 return true;
3220
3221 Values.push_back((uint8_t)CurrValue);
3222
3223 while (getLexer().is(AsmToken::Comma)) {
3224 Lex();
3225
3226 if (getParser().ParseAbsoluteExpression(CurrValue))
3227 return true;
3228
3229 Values.push_back((uint8_t)CurrValue);
3230 }
3231
3232 getStreamer().EmitCFIEscape(Values);
3233 return false;
3234}
3235
Rafael Espindola16d7d432012-01-23 21:51:52 +00003236/// ParseDirectiveCFISignalFrame
3237/// ::= .cfi_signal_frame
3238bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3239 SMLoc DirectiveLoc) {
3240 if (getLexer().isNot(AsmToken::EndOfStatement))
3241 return Error(getLexer().getLoc(),
3242 "unexpected token in '" + Directive + "' directive");
3243
3244 getStreamer().EmitCFISignalFrame();
3245
3246 return false;
3247}
3248
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003249/// ParseDirectiveMacrosOnOff
3250/// ::= .macros_on
3251/// ::= .macros_off
3252bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3253 SMLoc DirectiveLoc) {
3254 if (getLexer().isNot(AsmToken::EndOfStatement))
3255 return Error(getLexer().getLoc(),
3256 "unexpected token in '" + Directive + "' directive");
3257
3258 getParser().MacrosEnabled = Directive == ".macros_on";
3259
3260 return false;
3261}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003262
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003263/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003264/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003265bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3266 SMLoc DirectiveLoc) {
3267 StringRef Name;
3268 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003269 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003270
Rafael Espindola8a403d32012-08-08 14:51:03 +00003271 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003272 // Argument delimiter is initially unknown. It will be set by
3273 // ParseMacroArgument()
3274 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003275 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003276 for (;;) {
3277 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003278 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003279 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003280
3281 if (getLexer().is(AsmToken::Equal)) {
3282 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003283 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003284 return true;
3285 }
3286
Rafael Espindola65366442011-06-05 02:43:45 +00003287 Parameters.push_back(Parameter);
3288
Preston Gurd7b6f2032012-09-19 20:36:12 +00003289 if (getLexer().is(AsmToken::Comma))
3290 Lex();
3291 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003292 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003293 }
3294 }
3295
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003296 // Eat the end of statement.
3297 Lex();
3298
3299 AsmToken EndToken, StartToken = getTok();
3300
3301 // Lex the macro definition.
3302 for (;;) {
3303 // Check whether we have reached the end of the file.
3304 if (getLexer().is(AsmToken::Eof))
3305 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3306
3307 // Otherwise, check whether we have reach the .endmacro.
3308 if (getLexer().is(AsmToken::Identifier) &&
3309 (getTok().getIdentifier() == ".endm" ||
3310 getTok().getIdentifier() == ".endmacro")) {
3311 EndToken = getTok();
3312 Lex();
3313 if (getLexer().isNot(AsmToken::EndOfStatement))
3314 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3315 "' directive");
3316 break;
3317 }
3318
3319 // Otherwise, scan til the end of the statement.
3320 getParser().EatToEndOfStatement();
3321 }
3322
3323 if (getParser().MacroMap.lookup(Name)) {
3324 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3325 }
3326
3327 const char *BodyStart = StartToken.getLoc().getPointer();
3328 const char *BodyEnd = EndToken.getLoc().getPointer();
3329 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003330 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003331 return false;
3332}
3333
3334/// ParseDirectiveEndMacro
3335/// ::= .endm
3336/// ::= .endmacro
3337bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003338 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003339 if (getLexer().isNot(AsmToken::EndOfStatement))
3340 return TokError("unexpected token in '" + Directive + "' directive");
3341
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003342 // If we are inside a macro instantiation, terminate the current
3343 // instantiation.
3344 if (!getParser().ActiveMacros.empty()) {
3345 getParser().HandleMacroExit();
3346 return false;
3347 }
3348
3349 // Otherwise, this .endmacro is a stray entry in the file; well formed
3350 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003351 return TokError("unexpected '" + Directive + "' in file, "
3352 "no current macro definition");
3353}
3354
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003355/// ParseDirectivePurgeMacro
3356/// ::= .purgem
3357bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3358 SMLoc DirectiveLoc) {
3359 StringRef Name;
3360 if (getParser().ParseIdentifier(Name))
3361 return TokError("expected identifier in '.purgem' directive");
3362
3363 if (getLexer().isNot(AsmToken::EndOfStatement))
3364 return TokError("unexpected token in '.purgem' directive");
3365
3366 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3367 if (I == getParser().MacroMap.end())
3368 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3369
3370 // Undefine the macro.
3371 delete I->getValue();
3372 getParser().MacroMap.erase(I);
3373 return false;
3374}
3375
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003376bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003377 getParser().CheckForValidSection();
3378
3379 const MCExpr *Value;
3380
3381 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003382 return true;
3383
3384 if (getLexer().isNot(AsmToken::EndOfStatement))
3385 return TokError("unexpected token in directive");
3386
3387 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003388 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003389 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003390 getStreamer().EmitULEB128Value(Value);
3391
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003392 return false;
3393}
3394
Rafael Espindola761cb062012-06-03 23:57:14 +00003395Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003396 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003397
Rafael Espindola761cb062012-06-03 23:57:14 +00003398 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003399 for (;;) {
3400 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003401 if (getLexer().is(AsmToken::Eof)) {
3402 Error(DirectiveLoc, "no matching '.endr' in definition");
3403 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003404 }
3405
Rafael Espindola761cb062012-06-03 23:57:14 +00003406 if (Lexer.is(AsmToken::Identifier) &&
3407 (getTok().getIdentifier() == ".rept")) {
3408 ++NestLevel;
3409 }
3410
3411 // Otherwise, check whether we have reached the .endr.
3412 if (Lexer.is(AsmToken::Identifier) &&
3413 getTok().getIdentifier() == ".endr") {
3414 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003415 EndToken = getTok();
3416 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003417 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3418 TokError("unexpected token in '.endr' directive");
3419 return 0;
3420 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003421 break;
3422 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003423 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003424 }
3425
Rafael Espindola761cb062012-06-03 23:57:14 +00003426 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003427 EatToEndOfStatement();
3428 }
3429
3430 const char *BodyStart = StartToken.getLoc().getPointer();
3431 const char *BodyEnd = EndToken.getLoc().getPointer();
3432 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3433
Rafael Espindola761cb062012-06-03 23:57:14 +00003434 // We Are Anonymous.
3435 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003436 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003437 return new Macro(Name, Body, Parameters);
3438}
3439
3440void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3441 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003442 OS << ".endr\n";
3443
3444 MemoryBuffer *Instantiation =
3445 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3446
Rafael Espindola761cb062012-06-03 23:57:14 +00003447 // Create the macro instantiation object and add to the current macro
3448 // instantiation stack.
3449 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3450 getTok().getLoc(),
3451 Instantiation);
3452 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003453
Rafael Espindola761cb062012-06-03 23:57:14 +00003454 // Jump to the macro instantiation and prime the lexer.
3455 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3456 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3457 Lex();
3458}
3459
3460bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3461 int64_t Count;
3462 if (ParseAbsoluteExpression(Count))
3463 return TokError("unexpected token in '.rept' directive");
3464
3465 if (Count < 0)
3466 return TokError("Count is negative");
3467
3468 if (Lexer.isNot(AsmToken::EndOfStatement))
3469 return TokError("unexpected token in '.rept' directive");
3470
3471 // Eat the end of statement.
3472 Lex();
3473
3474 // Lex the rept definition.
3475 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3476 if (!M)
3477 return true;
3478
3479 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3480 // to hold the macro body with substitutions.
3481 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003482 MacroParameters Parameters;
3483 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003484 raw_svector_ostream OS(Buf);
3485 while (Count--) {
3486 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3487 return true;
3488 }
3489 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003490
3491 return false;
3492}
3493
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003494/// ParseDirectiveIrp
3495/// ::= .irp symbol,values
3496bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003497 MacroParameters Parameters;
3498 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003499
Preston Gurd6c9176a2012-09-19 20:29:04 +00003500 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003501 return TokError("expected identifier in '.irp' directive");
3502
3503 Parameters.push_back(Parameter);
3504
3505 if (Lexer.isNot(AsmToken::Comma))
3506 return TokError("expected comma in '.irp' directive");
3507
3508 Lex();
3509
Rafael Espindola8a403d32012-08-08 14:51:03 +00003510 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003511 if (ParseMacroArguments(0, A))
3512 return true;
3513
3514 // Eat the end of statement.
3515 Lex();
3516
3517 // Lex the irp 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;
3525 raw_svector_ostream OS(Buf);
3526
Rafael Espindola7996d042012-08-21 16:06:48 +00003527 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3528 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003529 Args.push_back(*i);
3530
3531 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3532 return true;
3533 }
3534
3535 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3536
3537 return false;
3538}
3539
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003540/// ParseDirectiveIrpc
3541/// ::= .irpc symbol,values
3542bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003543 MacroParameters Parameters;
3544 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003545
Preston Gurd6c9176a2012-09-19 20:29:04 +00003546 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003547 return TokError("expected identifier in '.irpc' directive");
3548
3549 Parameters.push_back(Parameter);
3550
3551 if (Lexer.isNot(AsmToken::Comma))
3552 return TokError("expected comma in '.irpc' directive");
3553
3554 Lex();
3555
Rafael Espindola8a403d32012-08-08 14:51:03 +00003556 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003557 if (ParseMacroArguments(0, A))
3558 return true;
3559
3560 if (A.size() != 1 || A.front().size() != 1)
3561 return TokError("unexpected token in '.irpc' directive");
3562
3563 // Eat the end of statement.
3564 Lex();
3565
3566 // Lex the irpc definition.
3567 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3568 if (!M)
3569 return true;
3570
3571 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3572 // to hold the macro body with substitutions.
3573 SmallString<256> Buf;
3574 raw_svector_ostream OS(Buf);
3575
3576 StringRef Values = A.front().front().getString();
3577 std::size_t I, End = Values.size();
3578 for (I = 0; I < End; ++I) {
3579 MacroArgument Arg;
3580 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3581
Rafael Espindola8a403d32012-08-08 14:51:03 +00003582 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003583 Args.push_back(Arg);
3584
3585 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3586 return true;
3587 }
3588
3589 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3590
3591 return false;
3592}
3593
Rafael Espindola761cb062012-06-03 23:57:14 +00003594bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3595 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003596 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003597
3598 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003599 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003600 assert(getLexer().is(AsmToken::EndOfStatement));
3601
Rafael Espindola761cb062012-06-03 23:57:14 +00003602 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003603 return false;
3604}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003605
Eli Friedman2128aae2012-10-22 23:58:19 +00003606bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3607 const MCExpr *Value;
3608 SMLoc ExprLoc = getLexer().getLoc();
3609 if (ParseExpression(Value))
3610 return true;
3611 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3612 if (!MCE)
3613 return Error(ExprLoc, "unexpected expression in _emit");
3614 uint64_t IntValue = MCE->getValue();
3615 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3616 return Error(ExprLoc, "literal value out of range for directive");
3617
3618 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3619 return false;
3620}
3621
Chad Rosierb1f8c132012-10-18 15:49:34 +00003622bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3623 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003624 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003625 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003626 SmallVectorImpl<std::string> &Clobbers,
3627 const MCInstrInfo *MII,
3628 const MCInstPrinter *IP,
3629 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003630 SmallVector<void *, 4> InputDecls;
3631 SmallVector<void *, 4> OutputDecls;
3632 SmallVector<bool, 4> InputDeclsOffsetOf;
3633 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003634 SmallVector<std::string, 4> InputConstraints;
3635 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003636 std::set<std::string> ClobberRegs;
3637
Chad Rosier4e472d22012-10-20 01:02:45 +00003638 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003639
3640 // Prime the lexer.
3641 Lex();
3642
3643 // While we have input, parse each statement.
3644 unsigned InputIdx = 0;
3645 unsigned OutputIdx = 0;
3646 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003647 ParseStatementInfo Info(&AsmStrRewrites);
3648 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003649 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003650
Eli Friedman2128aae2012-10-22 23:58:19 +00003651 if (Info.Opcode != ~0U) {
3652 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003653
3654 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003655 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3656 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003657
3658 // Immediate.
3659 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003660 if (Operand->needAsmRewrite())
3661 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3662 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003663 continue;
3664 }
3665
3666 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003667 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003668 unsigned NumDefs = Desc.getNumDefs();
3669 // Clobber.
3670 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3671 std::string Reg;
3672 raw_string_ostream OS(Reg);
3673 IP->printRegName(OS, Operand->getReg());
3674 ClobberRegs.insert(StringRef(OS.str()));
3675 }
3676 continue;
3677 }
3678
3679 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003680 unsigned Size;
3681 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3682 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003683 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003684 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003685 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003686 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003687 Operand->getStartLoc(),
3688 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003689 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003690 if (isOutput) {
3691 std::string Constraint = "=";
3692 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003693 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003694 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003695 Constraint += Operand->getConstraint().str();
3696 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003697 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003698 Operand->getStartLoc(),
3699 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003700 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003701 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003702 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003703 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003704 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003705 Operand->getStartLoc(),
3706 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003707 }
3708 }
3709 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003710 }
3711 }
3712
3713 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003714 NumOutputs = OutputDecls.size();
3715 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003716
3717 // Set the unique clobbers.
3718 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3719 E = ClobberRegs.end(); I != E; ++I)
3720 Clobbers.push_back(*I);
3721
3722 // Merge the various outputs and inputs. Output are expected first.
3723 if (NumOutputs || NumInputs) {
3724 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003725 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003726 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003727 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3728 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003729 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003730 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3731 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003732 }
3733 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003734 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3735 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003736 }
3737 }
3738
3739 // Build the IR assembly string.
3740 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003741 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003742 raw_string_ostream OS(AsmStringIR);
3743 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003744 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003745 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3746 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003747
Chad Rosier4e472d22012-10-20 01:02:45 +00003748 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003749
3750 // Emit everything up to the immediate/expression. If the previous rewrite
3751 // was a size directive, then this has already been done.
3752 if (PrevKind != AOK_SizeDirective)
3753 OS << StringRef(Start, Loc - Start);
3754 PrevKind = Kind;
3755
Chad Rosier5a719fc2012-10-23 17:43:43 +00003756 // Skip the original expression.
3757 if (Kind == AOK_Skip) {
3758 Start = Loc + (*I).Len;
3759 continue;
3760 }
3761
Chad Rosierb1f8c132012-10-18 15:49:34 +00003762 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003763 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003764 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003765 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003766 OS << Twine("$$");
3767 OS << (*I).Val;
3768 break;
3769 case AOK_ImmPrefix:
3770 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003771 break;
3772 case AOK_Input:
3773 OS << '$';
3774 OS << InputIdx++;
3775 break;
3776 case AOK_Output:
3777 OS << '$';
3778 OS << OutputIdx++;
3779 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003780 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003781 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003782 default: break;
3783 case 8: OS << "byte ptr "; break;
3784 case 16: OS << "word ptr "; break;
3785 case 32: OS << "dword ptr "; break;
3786 case 64: OS << "qword ptr "; break;
3787 case 80: OS << "xword ptr "; break;
3788 case 128: OS << "xmmword ptr "; break;
3789 case 256: OS << "ymmword ptr "; break;
3790 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003791 break;
3792 case AOK_Emit:
3793 OS << ".byte";
3794 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003795 case AOK_DotOperator:
3796 OS << (*I).Val;
3797 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003798 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003799
Chad Rosierb1f8c132012-10-18 15:49:34 +00003800 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003801 if (Kind != AOK_SizeDirective)
3802 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003803 }
3804
3805 // Emit the remainder of the asm string.
3806 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3807 if (Start != AsmEnd)
3808 OS << StringRef(Start, AsmEnd - Start);
3809
3810 AsmString = OS.str();
3811 return false;
3812}
3813
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003814/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003815MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003816 MCContext &C, MCStreamer &Out,
3817 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003818 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003819}