blob: 45fc475e341bbb95529a55343617312fb2530f56 [file] [log] [blame]
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002//
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// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Sandeep Patel34c1af82011-04-05 00:23:47 +000020#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar2c0843f2009-08-24 08:52:16 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Type.h"
Daniel Dunbar28df7a52009-12-03 09:13:49 +000024#include "llvm/Support/raw_ostream.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000025using namespace clang;
26using namespace CodeGen;
27
John McCallaeeb7012010-05-27 06:19:26 +000028static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
29 llvm::Value *Array,
30 llvm::Value *Value,
31 unsigned FirstIndex,
32 unsigned LastIndex) {
33 // Alternatively, we could emit this as a loop in the source.
34 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
35 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
36 Builder.CreateStore(Value, Cell);
37 }
38}
39
John McCalld608cdb2010-08-22 10:59:02 +000040static bool isAggregateTypeForABI(QualType T) {
John McCall9d232c82013-03-07 21:37:08 +000041 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalld608cdb2010-08-22 10:59:02 +000042 T->isMemberFunctionPointerType();
43}
44
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000045ABIInfo::~ABIInfo() {}
46
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000047static bool isRecordReturnIndirect(const RecordType *RT, CodeGen::CodeGenTypes &CGT) {
48 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
49 if (!RD)
50 return false;
51 return CGT.CGM.getCXXABI().isReturnTypeIndirect(RD);
52}
53
54
55static bool isRecordReturnIndirect(QualType T, CodeGen::CodeGenTypes &CGT) {
56 const RecordType *RT = T->getAs<RecordType>();
57 if (!RT)
58 return false;
59 return isRecordReturnIndirect(RT, CGT);
60}
61
62static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
63 CodeGen::CodeGenTypes &CGT) {
64 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
65 if (!RD)
66 return CGCXXABI::RAA_Default;
67 return CGT.CGM.getCXXABI().getRecordArgABI(RD);
68}
69
70static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
71 CodeGen::CodeGenTypes &CGT) {
72 const RecordType *RT = T->getAs<RecordType>();
73 if (!RT)
74 return CGCXXABI::RAA_Default;
75 return getRecordArgABI(RT, CGT);
76}
77
Chris Lattnerea044322010-07-29 02:01:43 +000078ASTContext &ABIInfo::getContext() const {
79 return CGT.getContext();
80}
81
82llvm::LLVMContext &ABIInfo::getVMContext() const {
83 return CGT.getLLVMContext();
84}
85
Micah Villmow25a6a842012-10-08 16:25:52 +000086const llvm::DataLayout &ABIInfo::getDataLayout() const {
87 return CGT.getDataLayout();
Chris Lattnerea044322010-07-29 02:01:43 +000088}
89
John McCall64aa4b32013-04-16 22:48:15 +000090const TargetInfo &ABIInfo::getTarget() const {
91 return CGT.getTarget();
92}
Chris Lattnerea044322010-07-29 02:01:43 +000093
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000094void ABIArgInfo::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +000095 raw_ostream &OS = llvm::errs();
Daniel Dunbar28df7a52009-12-03 09:13:49 +000096 OS << "(ABIArgInfo Kind=";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000097 switch (TheKind) {
98 case Direct:
Chris Lattner800588f2010-07-29 06:26:06 +000099 OS << "Direct Type=";
Chris Lattner2acc6e32011-07-18 04:24:23 +0000100 if (llvm::Type *Ty = getCoerceToType())
Chris Lattner800588f2010-07-29 06:26:06 +0000101 Ty->print(OS);
102 else
103 OS << "null";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000104 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000105 case Extend:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000106 OS << "Extend";
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000107 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000108 case Ignore:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000109 OS << "Ignore";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000110 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000111 case Indirect:
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000112 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenbergere9b5d772011-07-15 18:23:44 +0000113 << " ByVal=" << getIndirectByVal()
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000114 << " Realign=" << getIndirectRealign();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000115 break;
116 case Expand:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000117 OS << "Expand";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000118 break;
119 }
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000120 OS << ")\n";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000121}
122
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000123TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
124
John McCall49e34be2011-08-30 01:42:09 +0000125// If someone can figure out a general rule for this, that would be great.
126// It's probably just doomed to be platform-dependent, though.
127unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
128 // Verified for:
129 // x86-64 FreeBSD, Linux, Darwin
130 // x86-32 FreeBSD, Linux, Darwin
131 // PowerPC Linux, Darwin
132 // ARM Darwin (*not* EABI)
Tim Northoverc264e162013-01-31 12:13:10 +0000133 // AArch64 Linux
John McCall49e34be2011-08-30 01:42:09 +0000134 return 32;
135}
136
John McCallde5d3c72012-02-17 03:33:10 +0000137bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
138 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +0000139 // The following conventions are known to require this to be false:
140 // x86_stdcall
141 // MIPS
142 // For everything else, we just prefer false unless we opt out.
143 return false;
144}
145
Reid Kleckner3190ca92013-05-08 13:44:39 +0000146void
147TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
148 llvm::SmallString<24> &Opt) const {
149 // This assumes the user is passing a library name like "rt" instead of a
150 // filename like "librt.a/so", and that they don't care whether it's static or
151 // dynamic.
152 Opt = "-l";
153 Opt += Lib;
154}
155
Daniel Dunbar98303b92009-09-13 08:03:58 +0000156static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000157
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000158/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000159/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar98303b92009-09-13 08:03:58 +0000160static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
161 bool AllowArrays) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000162 if (FD->isUnnamedBitfield())
163 return true;
164
165 QualType FT = FD->getType();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000166
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000167 // Constant arrays of empty records count as empty, strip them off.
168 // Constant arrays of zero length always count as empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000169 if (AllowArrays)
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000170 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
171 if (AT->getSize() == 0)
172 return true;
Daniel Dunbar98303b92009-09-13 08:03:58 +0000173 FT = AT->getElementType();
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000174 }
Daniel Dunbar98303b92009-09-13 08:03:58 +0000175
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000176 const RecordType *RT = FT->getAs<RecordType>();
177 if (!RT)
178 return false;
179
180 // C++ record fields are never empty, at least in the Itanium ABI.
181 //
182 // FIXME: We should use a predicate for whether this behavior is true in the
183 // current ABI.
184 if (isa<CXXRecordDecl>(RT->getDecl()))
185 return false;
186
Daniel Dunbar98303b92009-09-13 08:03:58 +0000187 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000188}
189
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000190/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000191/// fields. Note that a structure with a flexible array member is not
192/// considered empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000193static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000194 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000195 if (!RT)
196 return 0;
197 const RecordDecl *RD = RT->getDecl();
198 if (RD->hasFlexibleArrayMember())
199 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000200
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000201 // If this is a C++ record, check the bases first.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000202 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000203 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
204 e = CXXRD->bases_end(); i != e; ++i)
205 if (!isEmptyRecord(Context, i->getType(), true))
206 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000207
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000208 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
209 i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000210 if (!isEmptyField(Context, *i, AllowArrays))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000211 return false;
212 return true;
213}
214
215/// isSingleElementStruct - Determine if a structure is a "single
216/// element struct", i.e. it has exactly one non-empty field or
217/// exactly one field which is itself a single element
218/// struct. Structures with flexible array members are never
219/// considered single element structs.
220///
221/// \return The field declaration for the single non-empty field, if
222/// it exists.
223static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
224 const RecordType *RT = T->getAsStructureType();
225 if (!RT)
226 return 0;
227
228 const RecordDecl *RD = RT->getDecl();
229 if (RD->hasFlexibleArrayMember())
230 return 0;
231
232 const Type *Found = 0;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000233
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000234 // If this is a C++ record, check the bases first.
235 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
236 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
237 e = CXXRD->bases_end(); i != e; ++i) {
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000238 // Ignore empty records.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000239 if (isEmptyRecord(Context, i->getType(), true))
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000240 continue;
241
242 // If we already found an element then this isn't a single-element struct.
243 if (Found)
244 return 0;
245
246 // If this is non-empty and not a single element struct, the composite
247 // cannot be a single element struct.
248 Found = isSingleElementStruct(i->getType(), Context);
249 if (!Found)
250 return 0;
251 }
252 }
253
254 // Check for single element.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000255 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
256 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000257 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000258 QualType FT = FD->getType();
259
260 // Ignore empty fields.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000261 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000262 continue;
263
264 // If we already found an element then this isn't a single-element
265 // struct.
266 if (Found)
267 return 0;
268
269 // Treat single element arrays as the element.
270 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
271 if (AT->getSize().getZExtValue() != 1)
272 break;
273 FT = AT->getElementType();
274 }
275
John McCalld608cdb2010-08-22 10:59:02 +0000276 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000277 Found = FT.getTypePtr();
278 } else {
279 Found = isSingleElementStruct(FT, Context);
280 if (!Found)
281 return 0;
282 }
283 }
284
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000285 // We don't consider a struct a single-element struct if it has
286 // padding beyond the element type.
287 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
288 return 0;
289
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000290 return Found;
291}
292
293static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmandb748a32012-11-29 23:21:04 +0000294 // Treat complex types as the element type.
295 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
296 Ty = CTy->getElementType();
297
298 // Check for a type which we know has a simple scalar argument-passing
299 // convention without any padding. (We're specifically looking for 32
300 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbara1842d32010-05-14 03:40:53 +0000301 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmandb748a32012-11-29 23:21:04 +0000302 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000303 return false;
304
305 uint64_t Size = Context.getTypeSize(Ty);
306 return Size == 32 || Size == 64;
307}
308
Daniel Dunbar53012f42009-11-09 01:33:53 +0000309/// canExpandIndirectArgument - Test whether an argument type which is to be
310/// passed indirectly (on the stack) would have the equivalent layout if it was
311/// expanded into separate arguments. If so, we prefer to do the latter to avoid
312/// inhibiting optimizations.
313///
314// FIXME: This predicate is missing many cases, currently it just follows
315// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
316// should probably make this smarter, or better yet make the LLVM backend
317// capable of handling it.
318static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
319 // We can only expand structure types.
320 const RecordType *RT = Ty->getAs<RecordType>();
321 if (!RT)
322 return false;
323
324 // We can only expand (C) structures.
325 //
326 // FIXME: This needs to be generalized to handle classes as well.
327 const RecordDecl *RD = RT->getDecl();
328 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
329 return false;
330
Eli Friedman506d4e32011-11-18 01:32:26 +0000331 uint64_t Size = 0;
332
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000333 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
334 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000335 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000336
337 if (!is32Or64BitBasicType(FD->getType(), Context))
338 return false;
339
340 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
341 // how to expand them yet, and the predicate for telling if a bitfield still
342 // counts as "basic" is more complicated than what we were doing previously.
343 if (FD->isBitField())
344 return false;
Eli Friedman506d4e32011-11-18 01:32:26 +0000345
346 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000347 }
348
Eli Friedman506d4e32011-11-18 01:32:26 +0000349 // Make sure there are not any holes in the struct.
350 if (Size != Context.getTypeSize(Ty))
351 return false;
352
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000353 return true;
354}
355
356namespace {
357/// DefaultABIInfo - The default implementation for ABI specific
358/// details. This implementation provides information which results in
359/// self-consistent and sensible LLVM IR generation, but does not
360/// conform to any particular ABI.
361class DefaultABIInfo : public ABIInfo {
Chris Lattnerea044322010-07-29 02:01:43 +0000362public:
363 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000364
Chris Lattnera3c109b2010-07-29 02:16:43 +0000365 ABIArgInfo classifyReturnType(QualType RetTy) const;
366 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000367
Chris Lattneree5dcd02010-07-29 02:31:05 +0000368 virtual void computeInfo(CGFunctionInfo &FI) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000369 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000370 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
371 it != ie; ++it)
Chris Lattnera3c109b2010-07-29 02:16:43 +0000372 it->info = classifyArgumentType(it->type);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000373 }
374
375 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
376 CodeGenFunction &CGF) const;
377};
378
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000379class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
380public:
Chris Lattnerea044322010-07-29 02:01:43 +0000381 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
382 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000383};
384
385llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
386 CodeGenFunction &CGF) const {
387 return 0;
388}
389
Chris Lattnera3c109b2010-07-29 02:16:43 +0000390ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung90306932011-11-03 00:59:44 +0000391 if (isAggregateTypeForABI(Ty)) {
392 // Records with non trivial destructors/constructors should not be passed
393 // by value.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000394 if (isRecordReturnIndirect(Ty, CGT))
Jan Wen Voung90306932011-11-03 00:59:44 +0000395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
396
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000397 return ABIArgInfo::getIndirect(0);
Jan Wen Voung90306932011-11-03 00:59:44 +0000398 }
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000399
Chris Lattnera14db752010-03-11 18:19:55 +0000400 // Treat an enum type as its underlying type.
401 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
402 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000403
Chris Lattnera14db752010-03-11 18:19:55 +0000404 return (Ty->isPromotableIntegerType() ?
405 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000406}
407
Bob Wilson0024f942011-01-10 23:54:17 +0000408ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
409 if (RetTy->isVoidType())
410 return ABIArgInfo::getIgnore();
411
412 if (isAggregateTypeForABI(RetTy))
413 return ABIArgInfo::getIndirect(0);
414
415 // Treat an enum type as its underlying type.
416 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
417 RetTy = EnumTy->getDecl()->getIntegerType();
418
419 return (RetTy->isPromotableIntegerType() ?
420 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
421}
422
Derek Schuff9ed63f82012-09-06 17:37:28 +0000423//===----------------------------------------------------------------------===//
424// le32/PNaCl bitcode ABI Implementation
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000425//
426// This is a simplified version of the x86_32 ABI. Arguments and return values
427// are always passed on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429
430class PNaClABIInfo : public ABIInfo {
431 public:
432 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
433
434 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000435 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000436
437 virtual void computeInfo(CGFunctionInfo &FI) const;
438 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const;
440};
441
442class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
443 public:
444 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
445 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
446};
447
448void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
449 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
450
Derek Schuff9ed63f82012-09-06 17:37:28 +0000451 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
452 it != ie; ++it)
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000453 it->info = classifyArgumentType(it->type);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000454 }
455
456llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
457 CodeGenFunction &CGF) const {
458 return 0;
459}
460
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000461/// \brief Classify argument of given type \p Ty.
462ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000463 if (isAggregateTypeForABI(Ty)) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000464 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
465 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000466 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000467 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
468 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000469 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000470 } else if (Ty->isFloatingType()) {
471 // Floating-point types don't go inreg.
472 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000473 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000474
475 return (Ty->isPromotableIntegerType() ?
476 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000477}
478
479ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
480 if (RetTy->isVoidType())
481 return ABIArgInfo::getIgnore();
482
Eli Benderskye45dfd12013-04-04 22:49:35 +0000483 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000484 if (isAggregateTypeForABI(RetTy))
485 return ABIArgInfo::getIndirect(0);
486
487 // Treat an enum type as its underlying type.
488 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
489 RetTy = EnumTy->getDecl()->getIntegerType();
490
491 return (RetTy->isPromotableIntegerType() ?
492 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
493}
494
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000495/// IsX86_MMXType - Return true if this is an MMX type.
496bool IsX86_MMXType(llvm::Type *IRType) {
497 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendlingbb465d72010-10-18 03:41:31 +0000498 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
499 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
500 IRType->getScalarSizeInBits() != 64;
501}
502
Jay Foadef6de3d2011-07-11 09:56:20 +0000503static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000505 llvm::Type* Ty) {
Bill Wendling0507be62011-03-07 22:47:14 +0000506 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy())
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000507 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
508 return Ty;
509}
510
Chris Lattnerdce5ad02010-06-28 20:05:43 +0000511//===----------------------------------------------------------------------===//
512// X86-32 ABI Implementation
513//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000514
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000515/// X86_32ABIInfo - The X86-32 ABI information.
516class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000517 enum Class {
518 Integer,
519 Float
520 };
521
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000522 static const unsigned MinABIStackAlignInBytes = 4;
523
David Chisnall1e4249c2009-08-17 23:08:21 +0000524 bool IsDarwinVectorABI;
525 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000526 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000527 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000528
529 static bool isRegisterSize(unsigned Size) {
530 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
531 }
532
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000533 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
534 unsigned callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000535
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000536 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
537 /// such that the argument will be passed in memory.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000538 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal,
539 unsigned &FreeRegs) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000540
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000541 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000542 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000543
Rafael Espindolab48280b2012-07-31 02:44:24 +0000544 Class classify(QualType Ty) const;
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000545 ABIArgInfo classifyReturnType(QualType RetTy,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000546 unsigned callingConvention) const;
Rafael Espindolab6932692012-10-24 01:58:58 +0000547 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs,
548 bool IsFastCall) const;
549 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000550 bool IsFastCall, bool &NeedsPadding) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000551
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000552public:
553
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000554 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000555 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
556 CodeGenFunction &CGF) const;
557
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000558 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000559 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000560 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000561 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000562};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000563
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000564class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
565public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000566 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000567 bool d, bool p, bool w, unsigned r)
568 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis74f72932010-02-13 15:54:06 +0000569
570 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
571 CodeGen::CodeGenModule &CGM) const;
John McCall6374c332010-03-06 00:35:14 +0000572
573 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
574 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000575 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000576 return 4;
577 }
578
579 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
580 llvm::Value *Address) const;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000581
Jay Foadef6de3d2011-07-11 09:56:20 +0000582 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000584 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000585 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
586 }
587
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000588};
589
590}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000591
592/// shouldReturnTypeInRegister - Determine if the given type should be
593/// passed in a register (for the Darwin ABI).
594bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000595 ASTContext &Context,
596 unsigned callingConvention) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000597 uint64_t Size = Context.getTypeSize(Ty);
598
599 // Type must be register sized.
600 if (!isRegisterSize(Size))
601 return false;
602
603 if (Ty->isVectorType()) {
604 // 64- and 128- bit vectors inside structures are not returned in
605 // registers.
606 if (Size == 64 || Size == 128)
607 return false;
608
609 return true;
610 }
611
Daniel Dunbar77115232010-05-15 00:00:30 +0000612 // If this is a builtin, pointer, enum, complex type, member pointer, or
613 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000614 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000615 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000616 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000617 return true;
618
619 // Arrays are treated like records.
620 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000621 return shouldReturnTypeInRegister(AT->getElementType(), Context,
622 callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000623
624 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000625 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000626 if (!RT) return false;
627
Anders Carlssona8874232010-01-27 03:25:19 +0000628 // FIXME: Traverse bases here too.
629
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000630 // For thiscall conventions, structures will never be returned in
631 // a register. This is for compatibility with the MSVC ABI
632 if (callingConvention == llvm::CallingConv::X86_ThisCall &&
633 RT->isStructureType()) {
634 return false;
635 }
636
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000637 // Structure types are passed in register if all fields would be
638 // passed in a register.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000639 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
640 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000641 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000642
643 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000644 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000645 continue;
646
647 // Check fields recursively.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000648 if (!shouldReturnTypeInRegister(FD->getType(), Context,
649 callingConvention))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000650 return false;
651 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000652 return true;
653}
654
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000655ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
656 unsigned callingConvention) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000657 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000658 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000659
Chris Lattnera3c109b2010-07-29 02:16:43 +0000660 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000661 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000662 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000663 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000664
665 // 128-bit vectors are a special case; they are returned in
666 // registers and we need to make sure to pick a type the LLVM
667 // backend will like.
668 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000669 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000670 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000671
672 // Always return in register if it fits in a general purpose
673 // register, or if it is 64 bits and has a single element.
674 if ((Size == 8 || Size == 16 || Size == 32) ||
675 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000676 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000677 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000678
679 return ABIArgInfo::getIndirect(0);
680 }
681
682 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000683 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000684
John McCalld608cdb2010-08-22 10:59:02 +0000685 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000686 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000687 if (isRecordReturnIndirect(RT, CGT))
Anders Carlsson40092972009-10-20 22:07:59 +0000688 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000689
Anders Carlsson40092972009-10-20 22:07:59 +0000690 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000691 if (RT->getDecl()->hasFlexibleArrayMember())
692 return ABIArgInfo::getIndirect(0);
Anders Carlsson40092972009-10-20 22:07:59 +0000693 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000694
David Chisnall1e4249c2009-08-17 23:08:21 +0000695 // If specified, structs and unions are always indirect.
696 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000697 return ABIArgInfo::getIndirect(0);
698
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000699 // Small structures which are register sized are generally returned
700 // in a register.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000701 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
702 callingConvention)) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000703 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000704
705 // As a special-case, if the struct is a "single-element" struct, and
706 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000707 // floating-point register. (MSVC does not apply this special case.)
708 // We apply a similar transformation for pointer types to improve the
709 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000710 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000711 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000712 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000713 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
714
715 // FIXME: We should be able to narrow this integer in cases with dead
716 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000717 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000718 }
719
720 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000721 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000722
Chris Lattnera3c109b2010-07-29 02:16:43 +0000723 // Treat an enum type as its underlying type.
724 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
725 RetTy = EnumTy->getDecl()->getIntegerType();
726
727 return (RetTy->isPromotableIntegerType() ?
728 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000729}
730
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000731static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
732 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
733}
734
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000735static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
736 const RecordType *RT = Ty->getAs<RecordType>();
737 if (!RT)
738 return 0;
739 const RecordDecl *RD = RT->getDecl();
740
741 // If this is a C++ record, check the bases first.
742 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
743 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
744 e = CXXRD->bases_end(); i != e; ++i)
745 if (!isRecordWithSSEVectorType(Context, i->getType()))
746 return false;
747
748 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
749 i != e; ++i) {
750 QualType FT = i->getType();
751
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000752 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000753 return true;
754
755 if (isRecordWithSSEVectorType(Context, FT))
756 return true;
757 }
758
759 return false;
760}
761
Daniel Dunbare59d8582010-09-16 20:42:06 +0000762unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
763 unsigned Align) const {
764 // Otherwise, if the alignment is less than or equal to the minimum ABI
765 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000766 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000767 return 0; // Use default alignment.
768
769 // On non-Darwin, the stack type alignment is always 4.
770 if (!IsDarwinVectorABI) {
771 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000772 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000773 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000774
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000775 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000776 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
777 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000778 return 16;
779
780 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000781}
782
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000783ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
784 unsigned &FreeRegs) const {
785 if (!ByVal) {
786 if (FreeRegs) {
787 --FreeRegs; // Non byval indirects just use one pointer.
788 return ABIArgInfo::getIndirectInReg(0, false);
789 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000790 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000791 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000792
Daniel Dunbare59d8582010-09-16 20:42:06 +0000793 // Compute the byval alignment.
794 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
795 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
796 if (StackAlign == 0)
Chris Lattnerde92d732011-05-22 23:35:00 +0000797 return ABIArgInfo::getIndirect(4);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000798
799 // If the stack alignment is less than the type alignment, realign the
800 // argument.
801 if (StackAlign < TypeAlign)
802 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
803 /*Realign=*/true);
804
805 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000806}
807
Rafael Espindolab48280b2012-07-31 02:44:24 +0000808X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
809 const Type *T = isSingleElementStruct(Ty, getContext());
810 if (!T)
811 T = Ty.getTypePtr();
812
813 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
814 BuiltinType::Kind K = BT->getKind();
815 if (K == BuiltinType::Float || K == BuiltinType::Double)
816 return Float;
817 }
818 return Integer;
819}
820
Rafael Espindolab6932692012-10-24 01:58:58 +0000821bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000822 bool IsFastCall, bool &NeedsPadding) const {
823 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000824 Class C = classify(Ty);
825 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000826 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000827
Rafael Espindolab6932692012-10-24 01:58:58 +0000828 unsigned Size = getContext().getTypeSize(Ty);
829 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000830
831 if (SizeInRegs == 0)
832 return false;
833
Rafael Espindolab48280b2012-07-31 02:44:24 +0000834 if (SizeInRegs > FreeRegs) {
835 FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000836 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000837 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000838
Rafael Espindolab48280b2012-07-31 02:44:24 +0000839 FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000840
841 if (IsFastCall) {
842 if (Size > 32)
843 return false;
844
845 if (Ty->isIntegralOrEnumerationType())
846 return true;
847
848 if (Ty->isPointerType())
849 return true;
850
851 if (Ty->isReferenceType())
852 return true;
853
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000854 if (FreeRegs)
855 NeedsPadding = true;
856
Rafael Espindolab6932692012-10-24 01:58:58 +0000857 return false;
858 }
859
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000860 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000861}
862
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000863ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Rafael Espindolab6932692012-10-24 01:58:58 +0000864 unsigned &FreeRegs,
865 bool IsFastCall) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000866 // FIXME: Set alignment on indirect arguments.
John McCalld608cdb2010-08-22 10:59:02 +0000867 if (isAggregateTypeForABI(Ty)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000868 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000869 if (IsWin32StructABI)
870 return getIndirectResult(Ty, true, FreeRegs);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000871
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000872 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
873 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
874
875 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000876 if (RT->getDecl()->hasFlexibleArrayMember())
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000877 return getIndirectResult(Ty, true, FreeRegs);
Anders Carlssona8874232010-01-27 03:25:19 +0000878 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000879
Eli Friedman5a4d3522011-11-18 00:28:11 +0000880 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +0000881 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000882 return ABIArgInfo::getIgnore();
883
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000884 llvm::LLVMContext &LLVMContext = getVMContext();
885 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
886 bool NeedsPadding;
887 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000888 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000889 SmallVector<llvm::Type*, 3> Elements;
890 for (unsigned I = 0; I < SizeInRegs; ++I)
891 Elements.push_back(Int32);
892 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
893 return ABIArgInfo::getDirectInReg(Result);
894 }
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000895 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000896
Daniel Dunbar53012f42009-11-09 01:33:53 +0000897 // Expand small (<= 128-bit) record types when we know that the stack layout
898 // of those arguments will match the struct. This is important because the
899 // LLVM backend isn't smart enough to remove byval, which inhibits many
900 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +0000901 if (getContext().getTypeSize(Ty) <= 4*32 &&
902 canExpandIndirectArgument(Ty, getContext()))
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000903 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000904
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000905 return getIndirectResult(Ty, true, FreeRegs);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000906 }
907
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000908 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +0000909 // On Darwin, some vectors are passed in memory, we handle this by passing
910 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000911 if (IsDarwinVectorABI) {
912 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000913 if ((Size == 8 || Size == 16 || Size == 32) ||
914 (Size == 64 && VT->getNumElements() == 1))
915 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
916 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000917 }
Bill Wendlingbb465d72010-10-18 03:41:31 +0000918
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000919 if (IsX86_MMXType(CGT.ConvertType(Ty)))
920 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000921
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000922 return ABIArgInfo::getDirect();
923 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000924
925
Chris Lattnera3c109b2010-07-29 02:16:43 +0000926 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
927 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000928
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000929 bool NeedsPadding;
930 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000931
932 if (Ty->isPromotableIntegerType()) {
933 if (InReg)
934 return ABIArgInfo::getExtendInReg();
935 return ABIArgInfo::getExtend();
936 }
937 if (InReg)
938 return ABIArgInfo::getDirectInReg();
939 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000940}
941
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000942void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
943 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
944 FI.getCallingConvention());
Rafael Espindolab48280b2012-07-31 02:44:24 +0000945
Rafael Espindolab6932692012-10-24 01:58:58 +0000946 unsigned CC = FI.getCallingConvention();
947 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall;
948 unsigned FreeRegs;
949 if (IsFastCall)
950 FreeRegs = 2;
951 else if (FI.getHasRegParm())
952 FreeRegs = FI.getRegParm();
953 else
954 FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000955
956 // If the return value is indirect, then the hidden argument is consuming one
957 // integer register.
958 if (FI.getReturnInfo().isIndirect() && FreeRegs) {
959 --FreeRegs;
960 ABIArgInfo &Old = FI.getReturnInfo();
961 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
962 Old.getIndirectByVal(),
963 Old.getIndirectRealign());
964 }
965
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000966 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
967 it != ie; ++it)
Rafael Espindolab6932692012-10-24 01:58:58 +0000968 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall);
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000969}
970
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000971llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
972 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +0000973 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000974
975 CGBuilderTy &Builder = CGF.Builder;
976 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
977 "ap");
978 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +0000979
980 // Compute if the address needs to be aligned
981 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
982 Align = getTypeStackAlignInBytes(Ty, Align);
983 Align = std::max(Align, 4U);
984 if (Align > 4) {
985 // addr = (addr + align - 1) & -align;
986 llvm::Value *Offset =
987 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
988 Addr = CGF.Builder.CreateGEP(Addr, Offset);
989 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
990 CGF.Int32Ty);
991 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
992 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
993 Addr->getType(),
994 "ap.cur.aligned");
995 }
996
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000997 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000998 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000999 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1000
1001 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001002 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001003 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001004 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001005 "ap.next");
1006 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1007
1008 return AddrTyped;
1009}
1010
Charles Davis74f72932010-02-13 15:54:06 +00001011void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1012 llvm::GlobalValue *GV,
1013 CodeGen::CodeGenModule &CGM) const {
1014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1015 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1016 // Get the LLVM function.
1017 llvm::Function *Fn = cast<llvm::Function>(GV);
1018
1019 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001020 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001021 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001022 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1023 llvm::AttributeSet::get(CGM.getLLVMContext(),
1024 llvm::AttributeSet::FunctionIndex,
1025 B));
Charles Davis74f72932010-02-13 15:54:06 +00001026 }
1027 }
1028}
1029
John McCall6374c332010-03-06 00:35:14 +00001030bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1031 CodeGen::CodeGenFunction &CGF,
1032 llvm::Value *Address) const {
1033 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001034
Chris Lattner8b418682012-02-07 00:39:47 +00001035 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001036
John McCall6374c332010-03-06 00:35:14 +00001037 // 0-7 are the eight integer registers; the order is different
1038 // on Darwin (for EH), but the range is the same.
1039 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001040 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001041
John McCall64aa4b32013-04-16 22:48:15 +00001042 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001043 // 12-16 are st(0..4). Not sure why we stop at 4.
1044 // These have size 16, which is sizeof(long double) on
1045 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001046 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001047 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001048
John McCall6374c332010-03-06 00:35:14 +00001049 } else {
1050 // 9 is %eflags, which doesn't get a size on Darwin for some
1051 // reason.
1052 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1053
1054 // 11-16 are st(0..5). Not sure why we stop at 5.
1055 // These have size 12, which is sizeof(long double) on
1056 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001057 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001058 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1059 }
John McCall6374c332010-03-06 00:35:14 +00001060
1061 return false;
1062}
1063
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001064//===----------------------------------------------------------------------===//
1065// X86-64 ABI Implementation
1066//===----------------------------------------------------------------------===//
1067
1068
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001069namespace {
1070/// X86_64ABIInfo - The X86_64 ABI information.
1071class X86_64ABIInfo : public ABIInfo {
1072 enum Class {
1073 Integer = 0,
1074 SSE,
1075 SSEUp,
1076 X87,
1077 X87Up,
1078 ComplexX87,
1079 NoClass,
1080 Memory
1081 };
1082
1083 /// merge - Implement the X86_64 ABI merging algorithm.
1084 ///
1085 /// Merge an accumulating classification \arg Accum with a field
1086 /// classification \arg Field.
1087 ///
1088 /// \param Accum - The accumulating classification. This should
1089 /// always be either NoClass or the result of a previous merge
1090 /// call. In addition, this should never be Memory (the caller
1091 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001092 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001093
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001094 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1095 ///
1096 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1097 /// final MEMORY or SSE classes when necessary.
1098 ///
1099 /// \param AggregateSize - The size of the current aggregate in
1100 /// the classification process.
1101 ///
1102 /// \param Lo - The classification for the parts of the type
1103 /// residing in the low word of the containing object.
1104 ///
1105 /// \param Hi - The classification for the parts of the type
1106 /// residing in the higher words of the containing object.
1107 ///
1108 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1109
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001110 /// classify - Determine the x86_64 register classes in which the
1111 /// given type T should be passed.
1112 ///
1113 /// \param Lo - The classification for the parts of the type
1114 /// residing in the low word of the containing object.
1115 ///
1116 /// \param Hi - The classification for the parts of the type
1117 /// residing in the high word of the containing object.
1118 ///
1119 /// \param OffsetBase - The bit offset of this type in the
1120 /// containing object. Some parameters are classified different
1121 /// depending on whether they straddle an eightbyte boundary.
1122 ///
1123 /// If a word is unused its result will be NoClass; if a type should
1124 /// be passed in Memory then at least the classification of \arg Lo
1125 /// will be Memory.
1126 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001127 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001128 ///
1129 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1130 /// also be ComplexX87.
Chris Lattner9c254f02010-06-29 06:01:59 +00001131 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001132
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001133 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001134 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1135 unsigned IROffset, QualType SourceTy,
1136 unsigned SourceOffset) const;
1137 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1138 unsigned IROffset, QualType SourceTy,
1139 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001140
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001141 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001142 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001143 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001144
1145 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001146 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001147 ///
1148 /// \param freeIntRegs - The number of free integer registers remaining
1149 /// available.
1150 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001151
Chris Lattnera3c109b2010-07-29 02:16:43 +00001152 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001153
Bill Wendlingbb465d72010-10-18 03:41:31 +00001154 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001155 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001156 unsigned &neededInt,
Bill Wendling99aaae82010-10-18 23:51:38 +00001157 unsigned &neededSSE) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001158
Eli Friedmanee1ad992011-12-02 00:11:43 +00001159 bool IsIllegalVectorType(QualType Ty) const;
1160
John McCall67a57732011-04-21 01:20:55 +00001161 /// The 0.98 ABI revision clarified a lot of ambiguities,
1162 /// unfortunately in ways that were not always consistent with
1163 /// certain previous compilers. In particular, platforms which
1164 /// required strict binary compatibility with older versions of GCC
1165 /// may need to exempt themselves.
1166 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001167 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001168 }
1169
Eli Friedmanee1ad992011-12-02 00:11:43 +00001170 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001171 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1172 // 64-bit hardware.
1173 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001174
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001175public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001176 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001177 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001178 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001179 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001180
John McCallde5d3c72012-02-17 03:33:10 +00001181 bool isPassedUsingAVXType(QualType type) const {
1182 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001183 // The freeIntRegs argument doesn't matter here.
1184 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE);
John McCallde5d3c72012-02-17 03:33:10 +00001185 if (info.isDirect()) {
1186 llvm::Type *ty = info.getCoerceToType();
1187 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1188 return (vectorTy->getBitWidth() > 128);
1189 }
1190 return false;
1191 }
1192
Chris Lattneree5dcd02010-07-29 02:31:05 +00001193 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001194
1195 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1196 CodeGenFunction &CGF) const;
1197};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001198
Chris Lattnerf13721d2010-08-31 16:44:54 +00001199/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001200class WinX86_64ABIInfo : public ABIInfo {
1201
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001202 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001203
Chris Lattnerf13721d2010-08-31 16:44:54 +00001204public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001205 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1206
1207 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001208
1209 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1210 CodeGenFunction &CGF) const;
1211};
1212
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001213class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1214public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001215 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffbabaf312012-10-11 15:52:22 +00001216 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCall6374c332010-03-06 00:35:14 +00001217
John McCallde5d3c72012-02-17 03:33:10 +00001218 const X86_64ABIInfo &getABIInfo() const {
1219 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1220 }
1221
John McCall6374c332010-03-06 00:35:14 +00001222 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1223 return 7;
1224 }
1225
1226 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1227 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001228 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001229
John McCallaeeb7012010-05-27 06:19:26 +00001230 // 0-15 are the 16 integer registers.
1231 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001232 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001233 return false;
1234 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001235
Jay Foadef6de3d2011-07-11 09:56:20 +00001236 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001237 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +00001238 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001239 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1240 }
1241
John McCallde5d3c72012-02-17 03:33:10 +00001242 bool isNoProtoCallVariadic(const CallArgList &args,
1243 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +00001244 // The default CC on x86-64 sets %al to the number of SSA
1245 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001246 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001247 // that when AVX types are involved: the ABI explicitly states it is
1248 // undefined, and it doesn't work in practice because of how the ABI
1249 // defines varargs anyway.
John McCallde5d3c72012-02-17 03:33:10 +00001250 if (fnType->getCallConv() == CC_Default || fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001251 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001252 for (CallArgList::const_iterator
1253 it = args.begin(), ie = args.end(); it != ie; ++it) {
1254 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1255 HasAVXType = true;
1256 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001257 }
1258 }
John McCallde5d3c72012-02-17 03:33:10 +00001259
Eli Friedman3ed79032011-12-01 04:53:19 +00001260 if (!HasAVXType)
1261 return true;
1262 }
John McCall01f151e2011-09-21 08:08:30 +00001263
John McCallde5d3c72012-02-17 03:33:10 +00001264 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001265 }
1266
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001267};
1268
Reid Kleckner3190ca92013-05-08 13:44:39 +00001269class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1270public:
1271 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned RegParms)
1272 : X86_32TargetCodeGenInfo(CGT, false, true, true, RegParms) {}
1273
1274 void getDependentLibraryOption(llvm::StringRef Lib,
1275 llvm::SmallString<24> &Opt) const {
1276 Opt = "/DEFAULTLIB:";
1277 Opt += Lib;
1278 }
1279};
1280
Chris Lattnerf13721d2010-08-31 16:44:54 +00001281class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1282public:
1283 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1284 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1285
1286 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1287 return 7;
1288 }
1289
1290 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1291 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001292 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001293
Chris Lattnerf13721d2010-08-31 16:44:54 +00001294 // 0-15 are the 16 integer registers.
1295 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001296 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001297 return false;
1298 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001299
1300 void getDependentLibraryOption(llvm::StringRef Lib,
1301 llvm::SmallString<24> &Opt) const {
1302 Opt = "/DEFAULTLIB:";
1303 Opt += Lib;
1304 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001305};
1306
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001307}
1308
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001309void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1310 Class &Hi) const {
1311 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1312 //
1313 // (a) If one of the classes is Memory, the whole argument is passed in
1314 // memory.
1315 //
1316 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1317 // memory.
1318 //
1319 // (c) If the size of the aggregate exceeds two eightbytes and the first
1320 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1321 // argument is passed in memory. NOTE: This is necessary to keep the
1322 // ABI working for processors that don't support the __m256 type.
1323 //
1324 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1325 //
1326 // Some of these are enforced by the merging logic. Others can arise
1327 // only with unions; for example:
1328 // union { _Complex double; unsigned; }
1329 //
1330 // Note that clauses (b) and (c) were added in 0.98.
1331 //
1332 if (Hi == Memory)
1333 Lo = Memory;
1334 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1335 Lo = Memory;
1336 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1337 Lo = Memory;
1338 if (Hi == SSEUp && Lo != SSE)
1339 Hi = SSE;
1340}
1341
Chris Lattner1090a9b2010-06-28 21:43:59 +00001342X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001343 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1344 // classified recursively so that always two fields are
1345 // considered. The resulting class is calculated according to
1346 // the classes of the fields in the eightbyte:
1347 //
1348 // (a) If both classes are equal, this is the resulting class.
1349 //
1350 // (b) If one of the classes is NO_CLASS, the resulting class is
1351 // the other class.
1352 //
1353 // (c) If one of the classes is MEMORY, the result is the MEMORY
1354 // class.
1355 //
1356 // (d) If one of the classes is INTEGER, the result is the
1357 // INTEGER.
1358 //
1359 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1360 // MEMORY is used as class.
1361 //
1362 // (f) Otherwise class SSE is used.
1363
1364 // Accum should never be memory (we should have returned) or
1365 // ComplexX87 (because this cannot be passed in a structure).
1366 assert((Accum != Memory && Accum != ComplexX87) &&
1367 "Invalid accumulated classification during merge.");
1368 if (Accum == Field || Field == NoClass)
1369 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001370 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001371 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001372 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001373 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001374 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001375 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001376 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1377 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001378 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001379 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001380}
1381
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001382void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001383 Class &Lo, Class &Hi) const {
1384 // FIXME: This code can be simplified by introducing a simple value class for
1385 // Class pairs with appropriate constructor methods for the various
1386 // situations.
1387
1388 // FIXME: Some of the split computations are wrong; unaligned vectors
1389 // shouldn't be passed in registers for example, so there is no chance they
1390 // can straddle an eightbyte. Verify & simplify.
1391
1392 Lo = Hi = NoClass;
1393
1394 Class &Current = OffsetBase < 64 ? Lo : Hi;
1395 Current = Memory;
1396
John McCall183700f2009-09-21 23:43:11 +00001397 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001398 BuiltinType::Kind k = BT->getKind();
1399
1400 if (k == BuiltinType::Void) {
1401 Current = NoClass;
1402 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1403 Lo = Integer;
1404 Hi = Integer;
1405 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1406 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001407 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1408 (k == BuiltinType::LongDouble &&
John McCall64aa4b32013-04-16 22:48:15 +00001409 getTarget().getTriple().getOS() == llvm::Triple::NaCl)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001410 Current = SSE;
1411 } else if (k == BuiltinType::LongDouble) {
1412 Lo = X87;
1413 Hi = X87Up;
1414 }
1415 // FIXME: _Decimal32 and _Decimal64 are SSE.
1416 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001417 return;
1418 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001419
Chris Lattner1090a9b2010-06-28 21:43:59 +00001420 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001421 // Classify the underlying integer type.
Chris Lattner9c254f02010-06-29 06:01:59 +00001422 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001423 return;
1424 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001425
Chris Lattner1090a9b2010-06-28 21:43:59 +00001426 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001427 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001428 return;
1429 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001430
Chris Lattner1090a9b2010-06-28 21:43:59 +00001431 if (Ty->isMemberPointerType()) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001432 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001433 Lo = Hi = Integer;
1434 else
1435 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001436 return;
1437 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001438
Chris Lattner1090a9b2010-06-28 21:43:59 +00001439 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001440 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001441 if (Size == 32) {
1442 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1443 // float> as integer.
1444 Current = Integer;
1445
1446 // If this type crosses an eightbyte boundary, it should be
1447 // split.
1448 uint64_t EB_Real = (OffsetBase) / 64;
1449 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1450 if (EB_Real != EB_Imag)
1451 Hi = Lo;
1452 } else if (Size == 64) {
1453 // gcc passes <1 x double> in memory. :(
1454 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1455 return;
1456
1457 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001458 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001459 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1460 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1461 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001462 Current = Integer;
1463 else
1464 Current = SSE;
1465
1466 // If this type crosses an eightbyte boundary, it should be
1467 // split.
1468 if (OffsetBase && OffsetBase != 64)
1469 Hi = Lo;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001470 } else if (Size == 128 || (HasAVX && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001471 // Arguments of 256-bits are split into four eightbyte chunks. The
1472 // least significant one belongs to class SSE and all the others to class
1473 // SSEUP. The original Lo and Hi design considers that types can't be
1474 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1475 // This design isn't correct for 256-bits, but since there're no cases
1476 // where the upper parts would need to be inspected, avoid adding
1477 // complexity and just consider Hi to match the 64-256 part.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001478 Lo = SSE;
1479 Hi = SSEUp;
1480 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001481 return;
1482 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001483
Chris Lattner1090a9b2010-06-28 21:43:59 +00001484 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001485 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001486
Chris Lattnerea044322010-07-29 02:01:43 +00001487 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001488 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001489 if (Size <= 64)
1490 Current = Integer;
1491 else if (Size <= 128)
1492 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001493 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001494 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001495 else if (ET == getContext().DoubleTy ||
1496 (ET == getContext().LongDoubleTy &&
John McCall64aa4b32013-04-16 22:48:15 +00001497 getTarget().getTriple().getOS() == llvm::Triple::NaCl))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001498 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001499 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001500 Current = ComplexX87;
1501
1502 // If this complex type crosses an eightbyte boundary then it
1503 // should be split.
1504 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001505 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001506 if (Hi == NoClass && EB_Real != EB_Imag)
1507 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001508
Chris Lattner1090a9b2010-06-28 21:43:59 +00001509 return;
1510 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001511
Chris Lattnerea044322010-07-29 02:01:43 +00001512 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001513 // Arrays are treated like structures.
1514
Chris Lattnerea044322010-07-29 02:01:43 +00001515 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001516
1517 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001518 // than four eightbytes, ..., it has class MEMORY.
1519 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001520 return;
1521
1522 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1523 // fields, it has class MEMORY.
1524 //
1525 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001526 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001527 return;
1528
1529 // Otherwise implement simplified merge. We could be smarter about
1530 // this, but it isn't worth it and would be harder to verify.
1531 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001532 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001533 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001534
1535 // The only case a 256-bit wide vector could be used is when the array
1536 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1537 // to work for sizes wider than 128, early check and fallback to memory.
1538 if (Size > 128 && EltSize != 256)
1539 return;
1540
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001541 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1542 Class FieldLo, FieldHi;
Chris Lattner9c254f02010-06-29 06:01:59 +00001543 classify(AT->getElementType(), Offset, FieldLo, FieldHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001544 Lo = merge(Lo, FieldLo);
1545 Hi = merge(Hi, FieldHi);
1546 if (Lo == Memory || Hi == Memory)
1547 break;
1548 }
1549
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001550 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001551 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00001552 return;
1553 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001554
Chris Lattner1090a9b2010-06-28 21:43:59 +00001555 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001556 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001557
1558 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001559 // than four eightbytes, ..., it has class MEMORY.
1560 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001561 return;
1562
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001563 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1564 // copy constructor or a non-trivial destructor, it is passed by invisible
1565 // reference.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001566 if (getRecordArgABI(RT, CGT))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001567 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001568
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001569 const RecordDecl *RD = RT->getDecl();
1570
1571 // Assume variable sized types are passed in memory.
1572 if (RD->hasFlexibleArrayMember())
1573 return;
1574
Chris Lattnerea044322010-07-29 02:01:43 +00001575 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001576
1577 // Reset Lo class, this will be recomputed.
1578 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001579
1580 // If this is a C++ record, classify the bases first.
1581 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1582 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1583 e = CXXRD->bases_end(); i != e; ++i) {
1584 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1585 "Unexpected base class!");
1586 const CXXRecordDecl *Base =
1587 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1588
1589 // Classify this field.
1590 //
1591 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1592 // single eightbyte, each is classified separately. Each eightbyte gets
1593 // initialized to class NO_CLASS.
1594 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001595 uint64_t Offset =
1596 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Chris Lattner9c254f02010-06-29 06:01:59 +00001597 classify(i->getType(), Offset, FieldLo, FieldHi);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001598 Lo = merge(Lo, FieldLo);
1599 Hi = merge(Hi, FieldHi);
1600 if (Lo == Memory || Hi == Memory)
1601 break;
1602 }
1603 }
1604
1605 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001606 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00001607 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001608 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001609 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1610 bool BitField = i->isBitField();
1611
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001612 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1613 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001614 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001615 // The only case a 256-bit wide vector could be used is when the struct
1616 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1617 // to work for sizes wider than 128, early check and fallback to memory.
1618 //
1619 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1620 Lo = Memory;
1621 return;
1622 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001623 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00001624 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001625 Lo = Memory;
1626 return;
1627 }
1628
1629 // Classify this field.
1630 //
1631 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1632 // exceeds a single eightbyte, each is classified
1633 // separately. Each eightbyte gets initialized to class
1634 // NO_CLASS.
1635 Class FieldLo, FieldHi;
1636
1637 // Bit-fields require special handling, they do not force the
1638 // structure to be passed in memory even if unaligned, and
1639 // therefore they can straddle an eightbyte.
1640 if (BitField) {
1641 // Ignore padding bit-fields.
1642 if (i->isUnnamedBitfield())
1643 continue;
1644
1645 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001646 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001647
1648 uint64_t EB_Lo = Offset / 64;
1649 uint64_t EB_Hi = (Offset + Size - 1) / 64;
1650 FieldLo = FieldHi = NoClass;
1651 if (EB_Lo) {
1652 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1653 FieldLo = NoClass;
1654 FieldHi = Integer;
1655 } else {
1656 FieldLo = Integer;
1657 FieldHi = EB_Hi ? Integer : NoClass;
1658 }
1659 } else
Chris Lattner9c254f02010-06-29 06:01:59 +00001660 classify(i->getType(), Offset, FieldLo, FieldHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001661 Lo = merge(Lo, FieldLo);
1662 Hi = merge(Hi, FieldHi);
1663 if (Lo == Memory || Hi == Memory)
1664 break;
1665 }
1666
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001667 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001668 }
1669}
1670
Chris Lattner9c254f02010-06-29 06:01:59 +00001671ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001672 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1673 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00001674 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001675 // Treat an enum type as its underlying type.
1676 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1677 Ty = EnumTy->getDecl()->getIntegerType();
1678
1679 return (Ty->isPromotableIntegerType() ?
1680 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1681 }
1682
1683 return ABIArgInfo::getIndirect(0);
1684}
1685
Eli Friedmanee1ad992011-12-02 00:11:43 +00001686bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1687 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1688 uint64_t Size = getContext().getTypeSize(VecTy);
1689 unsigned LargestVector = HasAVX ? 256 : 128;
1690 if (Size <= 64 || Size > LargestVector)
1691 return true;
1692 }
1693
1694 return false;
1695}
1696
Daniel Dunbaredfac032012-03-10 01:03:58 +00001697ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1698 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001699 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1700 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001701 //
1702 // This assumption is optimistic, as there could be free registers available
1703 // when we need to pass this argument in memory, and LLVM could try to pass
1704 // the argument in the free register. This does not seem to happen currently,
1705 // but this code would be much safer if we could mark the argument with
1706 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00001707 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001708 // Treat an enum type as its underlying type.
1709 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1710 Ty = EnumTy->getDecl()->getIntegerType();
1711
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001712 return (Ty->isPromotableIntegerType() ?
1713 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001714 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001715
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001716 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
1717 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001718
Chris Lattner855d2272011-05-22 23:21:23 +00001719 // Compute the byval alignment. We specify the alignment of the byval in all
1720 // cases so that the mid-level optimizer knows the alignment of the byval.
1721 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00001722
1723 // Attempt to avoid passing indirect results using byval when possible. This
1724 // is important for good codegen.
1725 //
1726 // We do this by coercing the value into a scalar type which the backend can
1727 // handle naturally (i.e., without using byval).
1728 //
1729 // For simplicity, we currently only do this when we have exhausted all of the
1730 // free integer registers. Doing this when there are free integer registers
1731 // would require more care, as we would have to ensure that the coerced value
1732 // did not claim the unused register. That would require either reording the
1733 // arguments to the function (so that any subsequent inreg values came first),
1734 // or only doing this optimization when there were no following arguments that
1735 // might be inreg.
1736 //
1737 // We currently expect it to be rare (particularly in well written code) for
1738 // arguments to be passed on the stack when there are still free integer
1739 // registers available (this would typically imply large structs being passed
1740 // by value), so this seems like a fair tradeoff for now.
1741 //
1742 // We can revisit this if the backend grows support for 'onstack' parameter
1743 // attributes. See PR12193.
1744 if (freeIntRegs == 0) {
1745 uint64_t Size = getContext().getTypeSize(Ty);
1746
1747 // If this type fits in an eightbyte, coerce it into the matching integral
1748 // type, which will end up on the stack (with alignment 8).
1749 if (Align == 8 && Size <= 64)
1750 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1751 Size));
1752 }
1753
Chris Lattner855d2272011-05-22 23:21:23 +00001754 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001755}
1756
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001757/// GetByteVectorType - The ABI specifies that a value should be passed in an
1758/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner0f408f52010-07-29 04:56:46 +00001759/// vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001760llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001761 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001762
Chris Lattner15842bd2010-07-29 05:02:29 +00001763 // Wrapper structs that just contain vectors are passed just like vectors,
1764 // strip them off if present.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001765 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner15842bd2010-07-29 05:02:29 +00001766 while (STy && STy->getNumElements() == 1) {
1767 IRType = STy->getElementType(0);
1768 STy = dyn_cast<llvm::StructType>(IRType);
1769 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001770
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00001771 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001772 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1773 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001774 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00001775 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00001776 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1777 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1778 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1779 EltTy->isIntegerTy(128)))
1780 return VT;
1781 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001782
Chris Lattner0f408f52010-07-29 04:56:46 +00001783 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1784}
1785
Chris Lattnere2962be2010-07-29 07:30:00 +00001786/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1787/// is known to either be off the end of the specified type or being in
1788/// alignment padding. The user type specified is known to be at most 128 bits
1789/// in size, and have passed through X86_64ABIInfo::classify with a successful
1790/// classification that put one of the two halves in the INTEGER class.
1791///
1792/// It is conservatively correct to return false.
1793static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1794 unsigned EndBit, ASTContext &Context) {
1795 // If the bytes being queried are off the end of the type, there is no user
1796 // data hiding here. This handles analysis of builtins, vectors and other
1797 // types that don't contain interesting padding.
1798 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1799 if (TySize <= StartBit)
1800 return true;
1801
Chris Lattner021c3a32010-07-29 07:43:55 +00001802 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1803 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1804 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1805
1806 // Check each element to see if the element overlaps with the queried range.
1807 for (unsigned i = 0; i != NumElts; ++i) {
1808 // If the element is after the span we care about, then we're done..
1809 unsigned EltOffset = i*EltSize;
1810 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001811
Chris Lattner021c3a32010-07-29 07:43:55 +00001812 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1813 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1814 EndBit-EltOffset, Context))
1815 return false;
1816 }
1817 // If it overlaps no elements, then it is safe to process as padding.
1818 return true;
1819 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001820
Chris Lattnere2962be2010-07-29 07:30:00 +00001821 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1822 const RecordDecl *RD = RT->getDecl();
1823 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001824
Chris Lattnere2962be2010-07-29 07:30:00 +00001825 // If this is a C++ record, check the bases first.
1826 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1827 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1828 e = CXXRD->bases_end(); i != e; ++i) {
1829 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1830 "Unexpected base class!");
1831 const CXXRecordDecl *Base =
1832 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001833
Chris Lattnere2962be2010-07-29 07:30:00 +00001834 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001835 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00001836 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001837
Chris Lattnere2962be2010-07-29 07:30:00 +00001838 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1839 if (!BitsContainNoUserData(i->getType(), BaseStart,
1840 EndBit-BaseOffset, Context))
1841 return false;
1842 }
1843 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001844
Chris Lattnere2962be2010-07-29 07:30:00 +00001845 // Verify that no field has data that overlaps the region of interest. Yes
1846 // this could be sped up a lot by being smarter about queried fields,
1847 // however we're only looking at structs up to 16 bytes, so we don't care
1848 // much.
1849 unsigned idx = 0;
1850 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1851 i != e; ++i, ++idx) {
1852 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001853
Chris Lattnere2962be2010-07-29 07:30:00 +00001854 // If we found a field after the region we care about, then we're done.
1855 if (FieldOffset >= EndBit) break;
1856
1857 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1858 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1859 Context))
1860 return false;
1861 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001862
Chris Lattnere2962be2010-07-29 07:30:00 +00001863 // If nothing in this record overlapped the area of interest, then we're
1864 // clean.
1865 return true;
1866 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001867
Chris Lattnere2962be2010-07-29 07:30:00 +00001868 return false;
1869}
1870
Chris Lattner0b362002010-07-29 18:39:32 +00001871/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1872/// float member at the specified offset. For example, {int,{float}} has a
1873/// float at offset 4. It is conservatively correct for this routine to return
1874/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001875static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00001876 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00001877 // Base case if we find a float.
1878 if (IROffset == 0 && IRType->isFloatTy())
1879 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001880
Chris Lattner0b362002010-07-29 18:39:32 +00001881 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001882 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00001883 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1884 unsigned Elt = SL->getElementContainingOffset(IROffset);
1885 IROffset -= SL->getElementOffset(Elt);
1886 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1887 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001888
Chris Lattner0b362002010-07-29 18:39:32 +00001889 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001890 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1891 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00001892 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1893 IROffset -= IROffset/EltSize*EltSize;
1894 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1895 }
1896
1897 return false;
1898}
1899
Chris Lattnerf47c9442010-07-29 18:13:09 +00001900
1901/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1902/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001903llvm::Type *X86_64ABIInfo::
1904GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00001905 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00001906 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00001907 // pass as float if the last 4 bytes is just padding. This happens for
1908 // structs that contain 3 floats.
1909 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1910 SourceOffset*8+64, getContext()))
1911 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001912
Chris Lattner0b362002010-07-29 18:39:32 +00001913 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1914 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1915 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00001916 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1917 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00001918 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001919
Chris Lattnerf47c9442010-07-29 18:13:09 +00001920 return llvm::Type::getDoubleTy(getVMContext());
1921}
1922
1923
Chris Lattner0d2656d2010-07-29 17:40:35 +00001924/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1925/// an 8-byte GPR. This means that we either have a scalar or we are talking
1926/// about the high or low part of an up-to-16-byte struct. This routine picks
1927/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00001928/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1929/// etc).
1930///
1931/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1932/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1933/// the 8-byte value references. PrefType may be null.
1934///
1935/// SourceTy is the source level type for the entire argument. SourceOffset is
1936/// an offset into this that we're processing (which is always either 0 or 8).
1937///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001938llvm::Type *X86_64ABIInfo::
1939GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00001940 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00001941 // If we're dealing with an un-offset LLVM IR type, then it means that we're
1942 // returning an 8-byte unit starting with it. See if we can safely use it.
1943 if (IROffset == 0) {
1944 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00001945 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
1946 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00001947 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00001948
Chris Lattnere2962be2010-07-29 07:30:00 +00001949 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1950 // goodness in the source type is just tail padding. This is allowed to
1951 // kick in for struct {double,int} on the int, but not on
1952 // struct{double,int,int} because we wouldn't return the second int. We
1953 // have to do this analysis on the source type because we can't depend on
1954 // unions being lowered a specific way etc.
1955 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00001956 IRType->isIntegerTy(32) ||
1957 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
1958 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
1959 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001960
Chris Lattnere2962be2010-07-29 07:30:00 +00001961 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
1962 SourceOffset*8+64, getContext()))
1963 return IRType;
1964 }
1965 }
Chris Lattner49382de2010-07-28 22:44:07 +00001966
Chris Lattner2acc6e32011-07-18 04:24:23 +00001967 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00001968 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00001969 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00001970 if (IROffset < SL->getSizeInBytes()) {
1971 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1972 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001973
Chris Lattner0d2656d2010-07-29 17:40:35 +00001974 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1975 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001976 }
Chris Lattner49382de2010-07-28 22:44:07 +00001977 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001978
Chris Lattner2acc6e32011-07-18 04:24:23 +00001979 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001980 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00001981 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00001982 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00001983 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
1984 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00001985 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001986
Chris Lattner49382de2010-07-28 22:44:07 +00001987 // Okay, we don't have any better idea of what to pass, so we pass this in an
1988 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00001989 unsigned TySizeInBytes =
1990 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00001991
Chris Lattner9e45a3d2010-07-29 17:34:39 +00001992 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001993
Chris Lattner49382de2010-07-28 22:44:07 +00001994 // It is always safe to classify this as an integer type up to i64 that
1995 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00001996 return llvm::IntegerType::get(getVMContext(),
1997 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00001998}
1999
Chris Lattner66e7b682010-09-01 00:50:20 +00002000
2001/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2002/// be used as elements of a two register pair to pass or return, return a
2003/// first class aggregate to represent them. For example, if the low part of
2004/// a by-value argument should be passed as i32* and the high part as float,
2005/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002006static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002007GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002008 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002009 // In order to correctly satisfy the ABI, we need to the high part to start
2010 // at offset 8. If the high and low parts we inferred are both 4-byte types
2011 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2012 // the second element at offset 8. Check for this:
2013 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2014 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmow25a6a842012-10-08 16:25:52 +00002015 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002016 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002017
Chris Lattner66e7b682010-09-01 00:50:20 +00002018 // To handle this, we have to increase the size of the low part so that the
2019 // second element will start at an 8 byte offset. We can't increase the size
2020 // of the second element because it might make us access off the end of the
2021 // struct.
2022 if (HiStart != 8) {
2023 // There are only two sorts of types the ABI generation code can produce for
2024 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2025 // Promote these to a larger type.
2026 if (Lo->isFloatTy())
2027 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2028 else {
2029 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2030 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2031 }
2032 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002033
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002034 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002035
2036
Chris Lattner66e7b682010-09-01 00:50:20 +00002037 // Verify that the second element is at an 8-byte offset.
2038 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2039 "Invalid x86-64 argument pair!");
2040 return Result;
2041}
2042
Chris Lattner519f68c2010-07-28 23:06:14 +00002043ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002044classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002045 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2046 // classification algorithm.
2047 X86_64ABIInfo::Class Lo, Hi;
2048 classify(RetTy, 0, Lo, Hi);
2049
2050 // Check some invariants.
2051 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002052 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2053
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002054 llvm::Type *ResType = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002055 switch (Lo) {
2056 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002057 if (Hi == NoClass)
2058 return ABIArgInfo::getIgnore();
2059 // If the low part is just padding, it takes no register, leave ResType
2060 // null.
2061 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2062 "Unknown missing lo part");
2063 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002064
2065 case SSEUp:
2066 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002067 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002068
2069 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2070 // hidden argument.
2071 case Memory:
2072 return getIndirectReturnResult(RetTy);
2073
2074 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2075 // available register of the sequence %rax, %rdx is used.
2076 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002077 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002078
Chris Lattnereb518b42010-07-29 21:42:50 +00002079 // If we have a sign or zero extended integer, make sure to return Extend
2080 // so that the parameter gets the right LLVM IR attributes.
2081 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2082 // Treat an enum type as its underlying type.
2083 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2084 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002085
Chris Lattnereb518b42010-07-29 21:42:50 +00002086 if (RetTy->isIntegralOrEnumerationType() &&
2087 RetTy->isPromotableIntegerType())
2088 return ABIArgInfo::getExtend();
2089 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002090 break;
2091
2092 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2093 // available SSE register of the sequence %xmm0, %xmm1 is used.
2094 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002095 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002096 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002097
2098 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2099 // returned on the X87 stack in %st0 as 80-bit x87 number.
2100 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002101 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002102 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002103
2104 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2105 // part of the value is returned in %st0 and the imaginary part in
2106 // %st1.
2107 case ComplexX87:
2108 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002109 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002110 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner519f68c2010-07-28 23:06:14 +00002111 NULL);
2112 break;
2113 }
2114
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002115 llvm::Type *HighPart = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002116 switch (Hi) {
2117 // Memory was handled previously and X87 should
2118 // never occur as a hi class.
2119 case Memory:
2120 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002121 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002122
2123 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002124 case NoClass:
2125 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002126
Chris Lattner3db4dde2010-09-01 00:20:33 +00002127 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002128 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002129 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2130 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002131 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002132 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002133 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002134 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2135 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002136 break;
2137
2138 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002139 // is passed in the next available eightbyte chunk if the last used
2140 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002141 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002142 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002143 case SSEUp:
2144 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002145 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002146 break;
2147
2148 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2149 // returned together with the previous X87 value in %st0.
2150 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002151 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002152 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002153 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002154 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002155 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002156 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002157 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2158 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002159 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002160 break;
2161 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002162
Chris Lattner3db4dde2010-09-01 00:20:33 +00002163 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002164 // known to pass in the high eightbyte of the result. We do this by forming a
2165 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002166 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002167 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002168
Chris Lattnereb518b42010-07-29 21:42:50 +00002169 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002170}
2171
Daniel Dunbaredfac032012-03-10 01:03:58 +00002172ABIArgInfo X86_64ABIInfo::classifyArgumentType(
2173 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE)
2174 const
2175{
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002176 X86_64ABIInfo::Class Lo, Hi;
Chris Lattner9c254f02010-06-29 06:01:59 +00002177 classify(Ty, 0, Lo, Hi);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002178
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002179 // Check some invariants.
2180 // FIXME: Enforce these by construction.
2181 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002182 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2183
2184 neededInt = 0;
2185 neededSSE = 0;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002186 llvm::Type *ResType = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002187 switch (Lo) {
2188 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002189 if (Hi == NoClass)
2190 return ABIArgInfo::getIgnore();
2191 // If the low part is just padding, it takes no register, leave ResType
2192 // null.
2193 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2194 "Unknown missing lo part");
2195 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002196
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002197 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2198 // on the stack.
2199 case Memory:
2200
2201 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2202 // COMPLEX_X87, it is passed in memory.
2203 case X87:
2204 case ComplexX87:
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002205 if (getRecordArgABI(Ty, CGT) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002206 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002207 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002208
2209 case SSEUp:
2210 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002211 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002212
2213 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2214 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2215 // and %r9 is used.
2216 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002217 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002218
Chris Lattner49382de2010-07-28 22:44:07 +00002219 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002220 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002221
2222 // If we have a sign or zero extended integer, make sure to return Extend
2223 // so that the parameter gets the right LLVM IR attributes.
2224 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2225 // Treat an enum type as its underlying type.
2226 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2227 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002228
Chris Lattnereb518b42010-07-29 21:42:50 +00002229 if (Ty->isIntegralOrEnumerationType() &&
2230 Ty->isPromotableIntegerType())
2231 return ABIArgInfo::getExtend();
2232 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002233
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002234 break;
2235
2236 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2237 // available SSE register is used, the registers are taken in the
2238 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002239 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002240 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002241 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002242 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002243 break;
2244 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002245 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002246
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002247 llvm::Type *HighPart = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002248 switch (Hi) {
2249 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002250 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002251 // which is passed in memory.
2252 case Memory:
2253 case X87:
2254 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002255 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002256
2257 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002258
Chris Lattner645406a2010-09-01 00:24:35 +00002259 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002260 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002261 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002262 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002263
Chris Lattner645406a2010-09-01 00:24:35 +00002264 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2265 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002266 break;
2267
2268 // X87Up generally doesn't occur here (long double is passed in
2269 // memory), except in situations involving unions.
2270 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002271 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002272 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002273
Chris Lattner645406a2010-09-01 00:24:35 +00002274 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2275 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002276
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002277 ++neededSSE;
2278 break;
2279
2280 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2281 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002282 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002283 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002284 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002285 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002286 break;
2287 }
2288
Chris Lattner645406a2010-09-01 00:24:35 +00002289 // If a high part was specified, merge it together with the low part. It is
2290 // known to pass in the high eightbyte of the result. We do this by forming a
2291 // first class struct aggregate with the high and low part: {low, high}
2292 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002293 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002294
Chris Lattnereb518b42010-07-29 21:42:50 +00002295 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002296}
2297
Chris Lattneree5dcd02010-07-29 02:31:05 +00002298void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002299
Chris Lattnera3c109b2010-07-29 02:16:43 +00002300 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002301
2302 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002303 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002304
2305 // If the return value is indirect, then the hidden argument is consuming one
2306 // integer register.
2307 if (FI.getReturnInfo().isIndirect())
2308 --freeIntRegs;
2309
2310 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2311 // get assigned (in left-to-right order) for passing as follows...
2312 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2313 it != ie; ++it) {
Bill Wendling99aaae82010-10-18 23:51:38 +00002314 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002315 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
2316 neededSSE);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002317
2318 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2319 // eightbyte of an argument, the whole argument is passed on the
2320 // stack. If registers have already been assigned for some
2321 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002322 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002323 freeIntRegs -= neededInt;
2324 freeSSERegs -= neededSSE;
2325 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002326 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002327 }
2328 }
2329}
2330
2331static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2332 QualType Ty,
2333 CodeGenFunction &CGF) {
2334 llvm::Value *overflow_arg_area_p =
2335 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2336 llvm::Value *overflow_arg_area =
2337 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2338
2339 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2340 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002341 // It isn't stated explicitly in the standard, but in practice we use
2342 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002343 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2344 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002345 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002346 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002347 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002348 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2349 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002350 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002351 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002352 overflow_arg_area =
2353 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2354 overflow_arg_area->getType(),
2355 "overflow_arg_area.align");
2356 }
2357
2358 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002359 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002360 llvm::Value *Res =
2361 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002362 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002363
2364 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2365 // l->overflow_arg_area + sizeof(type).
2366 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2367 // an 8 byte boundary.
2368
2369 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002370 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002371 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002372 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2373 "overflow_arg_area.next");
2374 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2375
2376 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2377 return Res;
2378}
2379
2380llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2381 CodeGenFunction &CGF) const {
2382 // Assume that va_list type is correct; should be pointer to LLVM type:
2383 // struct {
2384 // i32 gp_offset;
2385 // i32 fp_offset;
2386 // i8* overflow_arg_area;
2387 // i8* reg_save_area;
2388 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002389 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002390
Chris Lattnera14db752010-03-11 18:19:55 +00002391 Ty = CGF.getContext().getCanonicalType(Ty);
Daniel Dunbaredfac032012-03-10 01:03:58 +00002392 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002393
2394 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2395 // in the registers. If not go to step 7.
2396 if (!neededInt && !neededSSE)
2397 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2398
2399 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2400 // general purpose registers needed to pass type and num_fp to hold
2401 // the number of floating point registers needed.
2402
2403 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2404 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2405 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2406 //
2407 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2408 // register save space).
2409
2410 llvm::Value *InRegs = 0;
2411 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2412 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2413 if (neededInt) {
2414 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2415 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002416 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2417 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002418 }
2419
2420 if (neededSSE) {
2421 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2422 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2423 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002424 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2425 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002426 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2427 }
2428
2429 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2430 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2431 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2432 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2433
2434 // Emit code to load the value if it was passed in registers.
2435
2436 CGF.EmitBlock(InRegBlock);
2437
2438 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2439 // an offset of l->gp_offset and/or l->fp_offset. This may require
2440 // copying to a temporary location in case the parameter is passed
2441 // in different register classes or requires an alignment greater
2442 // than 8 for general purpose registers and 16 for XMM registers.
2443 //
2444 // FIXME: This really results in shameful code when we end up needing to
2445 // collect arguments from different places; often what should result in a
2446 // simple assembling of a structure from scattered addresses has many more
2447 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002448 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002449 llvm::Value *RegAddr =
2450 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2451 "reg_save_area");
2452 if (neededInt && neededSSE) {
2453 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002454 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002455 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002456 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
2457 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002458 llvm::Type *TyLo = ST->getElementType(0);
2459 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002460 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002461 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002462 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2463 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002464 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2465 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002466 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2467 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002468 llvm::Value *V =
2469 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2470 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2471 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2472 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2473
Owen Andersona1cf15f2009-07-14 23:10:40 +00002474 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002475 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002476 } else if (neededInt) {
2477 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2478 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002479 llvm::PointerType::getUnqual(LTy));
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002480 } else if (neededSSE == 1) {
2481 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2482 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2483 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002484 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002485 assert(neededSSE == 2 && "Invalid number of needed registers!");
2486 // SSE registers are spaced 16 bytes apart in the register save
2487 // area, we need to collect the two eightbytes together.
2488 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002489 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002490 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002491 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002492 llvm::PointerType::getUnqual(DoubleTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002493 llvm::StructType *ST = llvm::StructType::get(DoubleTy,
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002494 DoubleTy, NULL);
2495 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
2496 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2497 DblPtrTy));
2498 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2499 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2500 DblPtrTy));
2501 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2502 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2503 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002504 }
2505
2506 // AMD64-ABI 3.5.7p5: Step 5. Set:
2507 // l->gp_offset = l->gp_offset + num_gp * 8
2508 // l->fp_offset = l->fp_offset + num_fp * 16.
2509 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002510 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002511 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2512 gp_offset_p);
2513 }
2514 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002515 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002516 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2517 fp_offset_p);
2518 }
2519 CGF.EmitBranch(ContBlock);
2520
2521 // Emit code to load the value if it was passed in memory.
2522
2523 CGF.EmitBlock(InMemBlock);
2524 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2525
2526 // Return the appropriate result.
2527
2528 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002529 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002530 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002531 ResAddr->addIncoming(RegAddr, InRegBlock);
2532 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002533 return ResAddr;
2534}
2535
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002536ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002537
2538 if (Ty->isVoidType())
2539 return ABIArgInfo::getIgnore();
2540
2541 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2542 Ty = EnumTy->getDecl()->getIntegerType();
2543
2544 uint64_t Size = getContext().getTypeSize(Ty);
2545
2546 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002547 if (IsReturnType) {
2548 if (isRecordReturnIndirect(RT, CGT))
2549 return ABIArgInfo::getIndirect(0, false);
2550 } else {
2551 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
2552 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2553 }
2554
2555 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002556 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2557
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002558 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCall64aa4b32013-04-16 22:48:15 +00002559 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002560 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2561 Size));
2562
2563 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2564 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2565 if (Size <= 64 &&
NAKAMURA Takumiff8be0e2011-01-19 00:11:33 +00002566 (Size & (Size - 1)) == 0)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002567 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2568 Size));
2569
2570 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2571 }
2572
2573 if (Ty->isPromotableIntegerType())
2574 return ABIArgInfo::getExtend();
2575
2576 return ABIArgInfo::getDirect();
2577}
2578
2579void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2580
2581 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002582 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002583
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002584 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2585 it != ie; ++it)
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002586 it->info = classify(it->type, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002587}
2588
Chris Lattnerf13721d2010-08-31 16:44:54 +00002589llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2590 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00002591 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002592
Chris Lattnerf13721d2010-08-31 16:44:54 +00002593 CGBuilderTy &Builder = CGF.Builder;
2594 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2595 "ap");
2596 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2597 llvm::Type *PTy =
2598 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2599 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2600
2601 uint64_t Offset =
2602 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2603 llvm::Value *NextAddr =
2604 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2605 "ap.next");
2606 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2607
2608 return AddrTyped;
2609}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002610
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002611namespace {
2612
Derek Schuff263366f2012-10-16 22:30:41 +00002613class NaClX86_64ABIInfo : public ABIInfo {
2614 public:
2615 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2616 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2617 virtual void computeInfo(CGFunctionInfo &FI) const;
2618 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2619 CodeGenFunction &CGF) const;
2620 private:
2621 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2622 X86_64ABIInfo NInfo; // Used for everything else.
2623};
2624
2625class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2626 public:
2627 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2628 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2629};
2630
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002631}
2632
Derek Schuff263366f2012-10-16 22:30:41 +00002633void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2634 if (FI.getASTCallingConvention() == CC_PnaclCall)
2635 PInfo.computeInfo(FI);
2636 else
2637 NInfo.computeInfo(FI);
2638}
2639
2640llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2641 CodeGenFunction &CGF) const {
2642 // Always use the native convention; calling pnacl-style varargs functions
2643 // is unuspported.
2644 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2645}
2646
2647
John McCallec853ba2010-03-11 00:10:12 +00002648// PowerPC-32
2649
2650namespace {
2651class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2652public:
Chris Lattnerea044322010-07-29 02:01:43 +00002653 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002654
John McCallec853ba2010-03-11 00:10:12 +00002655 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2656 // This is recovered from gcc output.
2657 return 1; // r1 is the dedicated stack pointer
2658 }
2659
2660 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002661 llvm::Value *Address) const;
John McCallec853ba2010-03-11 00:10:12 +00002662};
2663
2664}
2665
2666bool
2667PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2668 llvm::Value *Address) const {
2669 // This is calculated from the LLVM and GCC tables and verified
2670 // against gcc output. AFAIK all ABIs use the same encoding.
2671
2672 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00002673
Chris Lattner8b418682012-02-07 00:39:47 +00002674 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00002675 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2676 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2677 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2678
2679 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00002680 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00002681
2682 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00002683 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00002684
2685 // 64-76 are various 4-byte special-purpose registers:
2686 // 64: mq
2687 // 65: lr
2688 // 66: ctr
2689 // 67: ap
2690 // 68-75 cr0-7
2691 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00002692 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00002693
2694 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00002695 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00002696
2697 // 109: vrsave
2698 // 110: vscr
2699 // 111: spe_acc
2700 // 112: spefscr
2701 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00002702 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00002703
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002704 return false;
John McCallec853ba2010-03-11 00:10:12 +00002705}
2706
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002707// PowerPC-64
2708
2709namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002710/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2711class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2712
2713public:
2714 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2715
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002716 bool isPromotableTypeForABI(QualType Ty) const;
2717
2718 ABIArgInfo classifyReturnType(QualType RetTy) const;
2719 ABIArgInfo classifyArgumentType(QualType Ty) const;
2720
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002721 // TODO: We can add more logic to computeInfo to improve performance.
2722 // Example: For aggregate arguments that fit in a register, we could
2723 // use getDirectInReg (as is done below for structs containing a single
2724 // floating-point value) to avoid pushing them to memory on function
2725 // entry. This would require changing the logic in PPCISelLowering
2726 // when lowering the parameters in the caller and args in the callee.
2727 virtual void computeInfo(CGFunctionInfo &FI) const {
2728 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2729 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2730 it != ie; ++it) {
2731 // We rely on the default argument classification for the most part.
2732 // One exception: An aggregate containing a single floating-point
2733 // item must be passed in a register if one is available.
2734 const Type *T = isSingleElementStruct(it->type, getContext());
2735 if (T) {
2736 const BuiltinType *BT = T->getAs<BuiltinType>();
2737 if (BT && BT->isFloatingPoint()) {
2738 QualType QT(T, 0);
2739 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2740 continue;
2741 }
2742 }
2743 it->info = classifyArgumentType(it->type);
2744 }
2745 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002746
2747 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2748 QualType Ty,
2749 CodeGenFunction &CGF) const;
2750};
2751
2752class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2753public:
2754 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2755 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2756
2757 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2758 // This is recovered from gcc output.
2759 return 1; // r1 is the dedicated stack pointer
2760 }
2761
2762 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2763 llvm::Value *Address) const;
2764};
2765
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002766class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2767public:
2768 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2769
2770 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2771 // This is recovered from gcc output.
2772 return 1; // r1 is the dedicated stack pointer
2773 }
2774
2775 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2776 llvm::Value *Address) const;
2777};
2778
2779}
2780
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002781// Return true if the ABI requires Ty to be passed sign- or zero-
2782// extended to 64 bits.
2783bool
2784PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2785 // Treat an enum type as its underlying type.
2786 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2787 Ty = EnumTy->getDecl()->getIntegerType();
2788
2789 // Promotable integer types are required to be promoted by the ABI.
2790 if (Ty->isPromotableIntegerType())
2791 return true;
2792
2793 // In addition to the usual promotable integer types, we also need to
2794 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2795 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2796 switch (BT->getKind()) {
2797 case BuiltinType::Int:
2798 case BuiltinType::UInt:
2799 return true;
2800 default:
2801 break;
2802 }
2803
2804 return false;
2805}
2806
2807ABIArgInfo
2808PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidtc9715fc2012-11-27 02:46:43 +00002809 if (Ty->isAnyComplexType())
2810 return ABIArgInfo::getDirect();
2811
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002812 if (isAggregateTypeForABI(Ty)) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002813 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
2814 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002815
2816 return ABIArgInfo::getIndirect(0);
2817 }
2818
2819 return (isPromotableTypeForABI(Ty) ?
2820 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2821}
2822
2823ABIArgInfo
2824PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2825 if (RetTy->isVoidType())
2826 return ABIArgInfo::getIgnore();
2827
Bill Schmidt9e6111a2012-12-17 04:20:17 +00002828 if (RetTy->isAnyComplexType())
2829 return ABIArgInfo::getDirect();
2830
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002831 if (isAggregateTypeForABI(RetTy))
2832 return ABIArgInfo::getIndirect(0);
2833
2834 return (isPromotableTypeForABI(RetTy) ?
2835 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2836}
2837
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002838// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2839llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2840 QualType Ty,
2841 CodeGenFunction &CGF) const {
2842 llvm::Type *BP = CGF.Int8PtrTy;
2843 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2844
2845 CGBuilderTy &Builder = CGF.Builder;
2846 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2847 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2848
Bill Schmidt19f8e852013-01-14 17:45:36 +00002849 // Update the va_list pointer. The pointer should be bumped by the
2850 // size of the object. We can trust getTypeSize() except for a complex
2851 // type whose base type is smaller than a doubleword. For these, the
2852 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002853 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00002854 QualType BaseTy;
2855 unsigned CplxBaseSize = 0;
2856
2857 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2858 BaseTy = CTy->getElementType();
2859 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2860 if (CplxBaseSize < 8)
2861 SizeInBytes = 16;
2862 }
2863
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002864 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2865 llvm::Value *NextAddr =
2866 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2867 "ap.next");
2868 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2869
Bill Schmidt19f8e852013-01-14 17:45:36 +00002870 // If we have a complex type and the base type is smaller than 8 bytes,
2871 // the ABI calls for the real and imaginary parts to be right-adjusted
2872 // in separate doublewords. However, Clang expects us to produce a
2873 // pointer to a structure with the two parts packed tightly. So generate
2874 // loads of the real and imaginary parts relative to the va_list pointer,
2875 // and store them to a temporary structure.
2876 if (CplxBaseSize && CplxBaseSize < 8) {
2877 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2878 llvm::Value *ImagAddr = RealAddr;
2879 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2880 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2881 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2882 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2883 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2884 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2885 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2886 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2887 "vacplx");
2888 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2889 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2890 Builder.CreateStore(Real, RealPtr, false);
2891 Builder.CreateStore(Imag, ImagPtr, false);
2892 return Ptr;
2893 }
2894
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002895 // If the argument is smaller than 8 bytes, it is right-adjusted in
2896 // its doubleword slot. Adjust the pointer to pick it up from the
2897 // correct offset.
2898 if (SizeInBytes < 8) {
2899 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2900 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2901 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2902 }
2903
2904 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2905 return Builder.CreateBitCast(Addr, PTy);
2906}
2907
2908static bool
2909PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2910 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002911 // This is calculated from the LLVM and GCC tables and verified
2912 // against gcc output. AFAIK all ABIs use the same encoding.
2913
2914 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2915
2916 llvm::IntegerType *i8 = CGF.Int8Ty;
2917 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2918 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2919 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2920
2921 // 0-31: r0-31, the 8-byte general-purpose registers
2922 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
2923
2924 // 32-63: fp0-31, the 8-byte floating-point registers
2925 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2926
2927 // 64-76 are various 4-byte special-purpose registers:
2928 // 64: mq
2929 // 65: lr
2930 // 66: ctr
2931 // 67: ap
2932 // 68-75 cr0-7
2933 // 76: xer
2934 AssignToArrayRange(Builder, Address, Four8, 64, 76);
2935
2936 // 77-108: v0-31, the 16-byte vector registers
2937 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2938
2939 // 109: vrsave
2940 // 110: vscr
2941 // 111: spe_acc
2942 // 112: spefscr
2943 // 113: sfp
2944 AssignToArrayRange(Builder, Address, Four8, 109, 113);
2945
2946 return false;
2947}
John McCallec853ba2010-03-11 00:10:12 +00002948
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002949bool
2950PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
2951 CodeGen::CodeGenFunction &CGF,
2952 llvm::Value *Address) const {
2953
2954 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
2955}
2956
2957bool
2958PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2959 llvm::Value *Address) const {
2960
2961 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
2962}
2963
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002964//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00002965// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002966//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00002967
2968namespace {
2969
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002970class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00002971public:
2972 enum ABIKind {
2973 APCS = 0,
2974 AAPCS = 1,
2975 AAPCS_VFP
2976 };
2977
2978private:
2979 ABIKind Kind;
2980
2981public:
John McCallbd7370a2013-02-28 19:01:20 +00002982 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
2983 setRuntimeCC();
2984 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00002985
John McCall49e34be2011-08-30 01:42:09 +00002986 bool isEABI() const {
John McCall64aa4b32013-04-16 22:48:15 +00002987 StringRef Env = getTarget().getTriple().getEnvironmentName();
Logan Chien94a71422012-09-02 09:30:11 +00002988 return (Env == "gnueabi" || Env == "eabi" ||
2989 Env == "android" || Env == "androideabi");
John McCall49e34be2011-08-30 01:42:09 +00002990 }
2991
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00002992private:
2993 ABIKind getABIKind() const { return Kind; }
2994
Chris Lattnera3c109b2010-07-29 02:16:43 +00002995 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Ren710c5172012-10-31 19:02:26 +00002996 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
2997 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00002998 bool &IsHA) const;
Manman Ren97f81572012-10-16 19:18:39 +00002999 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003000
Chris Lattneree5dcd02010-07-29 02:31:05 +00003001 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003002
3003 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3004 CodeGenFunction &CGF) const;
John McCallbd7370a2013-02-28 19:01:20 +00003005
3006 llvm::CallingConv::ID getLLVMDefaultCC() const;
3007 llvm::CallingConv::ID getABIDefaultCC() const;
3008 void setRuntimeCC();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003009};
3010
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003011class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3012public:
Chris Lattnerea044322010-07-29 02:01:43 +00003013 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3014 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00003015
John McCall49e34be2011-08-30 01:42:09 +00003016 const ARMABIInfo &getABIInfo() const {
3017 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3018 }
3019
John McCall6374c332010-03-06 00:35:14 +00003020 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3021 return 13;
3022 }
Roman Divacky09345d12011-05-18 19:36:54 +00003023
Chris Lattner5f9e2722011-07-23 10:55:15 +00003024 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCallf85e1932011-06-15 23:02:42 +00003025 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3026 }
3027
Roman Divacky09345d12011-05-18 19:36:54 +00003028 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3029 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003030 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00003031
3032 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00003033 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00003034 return false;
3035 }
John McCall49e34be2011-08-30 01:42:09 +00003036
3037 unsigned getSizeOfUnwindException() const {
3038 if (getABIInfo().isEABI()) return 88;
3039 return TargetCodeGenInfo::getSizeOfUnwindException();
3040 }
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003041};
3042
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003043}
3044
Chris Lattneree5dcd02010-07-29 02:31:05 +00003045void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00003046 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Ren710c5172012-10-31 19:02:26 +00003047 // VFP registers allocated so far.
Manman Renb3fa55f2012-10-30 23:21:41 +00003048 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3049 // VFP registers of the appropriate type unallocated then the argument is
3050 // allocated to the lowest-numbered sequence of such registers.
3051 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3052 // unallocated are marked as unavailable.
3053 unsigned AllocatedVFP = 0;
Manman Ren710c5172012-10-31 19:02:26 +00003054 int VFPRegs[16] = { 0 };
Chris Lattnera3c109b2010-07-29 02:16:43 +00003055 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003056 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Renb3fa55f2012-10-30 23:21:41 +00003057 it != ie; ++it) {
3058 unsigned PreAllocation = AllocatedVFP;
3059 bool IsHA = false;
3060 // 6.1.2.3 There is one VFP co-processor register class using registers
3061 // s0-s15 (d0-d7) for passing arguments.
3062 const unsigned NumVFPs = 16;
Manman Ren710c5172012-10-31 19:02:26 +00003063 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Renb3fa55f2012-10-30 23:21:41 +00003064 // If we do not have enough VFP registers for the HA, any VFP registers
3065 // that are unallocated are marked as unavailable. To achieve this, we add
3066 // padding of (NumVFPs - PreAllocation) floats.
3067 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3068 llvm::Type *PaddingTy = llvm::ArrayType::get(
3069 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3070 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3071 }
3072 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003073
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003074 // Always honor user-specified calling convention.
3075 if (FI.getCallingConvention() != llvm::CallingConv::C)
3076 return;
3077
John McCallbd7370a2013-02-28 19:01:20 +00003078 llvm::CallingConv::ID cc = getRuntimeCC();
3079 if (cc != llvm::CallingConv::C)
3080 FI.setEffectiveCallingConvention(cc);
3081}
Rafael Espindola25117ab2010-06-16 16:13:39 +00003082
John McCallbd7370a2013-02-28 19:01:20 +00003083/// Return the default calling convention that LLVM will use.
3084llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3085 // The default calling convention that LLVM will infer.
John McCall64aa4b32013-04-16 22:48:15 +00003086 if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
John McCallbd7370a2013-02-28 19:01:20 +00003087 return llvm::CallingConv::ARM_AAPCS_VFP;
3088 else if (isEABI())
3089 return llvm::CallingConv::ARM_AAPCS;
3090 else
3091 return llvm::CallingConv::ARM_APCS;
3092}
3093
3094/// Return the calling convention that our ABI would like us to use
3095/// as the C calling convention.
3096llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003097 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00003098 case APCS: return llvm::CallingConv::ARM_APCS;
3099 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3100 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003101 }
John McCallbd7370a2013-02-28 19:01:20 +00003102 llvm_unreachable("bad ABI kind");
3103}
3104
3105void ARMABIInfo::setRuntimeCC() {
3106 assert(getRuntimeCC() == llvm::CallingConv::C);
3107
3108 // Don't muddy up the IR with a ton of explicit annotations if
3109 // they'd just match what LLVM will infer from the triple.
3110 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3111 if (abiCC != getLLVMDefaultCC())
3112 RuntimeCC = abiCC;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003113}
3114
Bob Wilson194f06a2011-08-03 05:58:22 +00003115/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3116/// aggregate. If HAMembers is non-null, the number of base elements
3117/// contained in the type is returned through it; this is used for the
3118/// recursive calls that check aggregate component types.
3119static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3120 ASTContext &Context,
3121 uint64_t *HAMembers = 0) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003122 uint64_t Members = 0;
Bob Wilson194f06a2011-08-03 05:58:22 +00003123 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3124 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3125 return false;
3126 Members *= AT->getSize().getZExtValue();
3127 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3128 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003129 if (RD->hasFlexibleArrayMember())
Bob Wilson194f06a2011-08-03 05:58:22 +00003130 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003131
Bob Wilson194f06a2011-08-03 05:58:22 +00003132 Members = 0;
3133 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3134 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003135 const FieldDecl *FD = *i;
Bob Wilson194f06a2011-08-03 05:58:22 +00003136 uint64_t FldMembers;
3137 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3138 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003139
3140 Members = (RD->isUnion() ?
3141 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilson194f06a2011-08-03 05:58:22 +00003142 }
3143 } else {
3144 Members = 1;
3145 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3146 Members = 2;
3147 Ty = CT->getElementType();
3148 }
3149
3150 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3151 // double, or 64-bit or 128-bit vectors.
3152 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3153 if (BT->getKind() != BuiltinType::Float &&
Tim Northoveradfa45f2012-07-20 22:29:29 +00003154 BT->getKind() != BuiltinType::Double &&
3155 BT->getKind() != BuiltinType::LongDouble)
Bob Wilson194f06a2011-08-03 05:58:22 +00003156 return false;
3157 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3158 unsigned VecSize = Context.getTypeSize(VT);
3159 if (VecSize != 64 && VecSize != 128)
3160 return false;
3161 } else {
3162 return false;
3163 }
3164
3165 // The base type must be the same for all members. Vector types of the
3166 // same total size are treated as being equivalent here.
3167 const Type *TyPtr = Ty.getTypePtr();
3168 if (!Base)
3169 Base = TyPtr;
3170 if (Base != TyPtr &&
3171 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3172 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3173 return false;
3174 }
3175
3176 // Homogeneous Aggregates can have at most 4 members of the base type.
3177 if (HAMembers)
3178 *HAMembers = Members;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003179
3180 return (Members > 0 && Members <= 4);
Bob Wilson194f06a2011-08-03 05:58:22 +00003181}
3182
Manman Ren710c5172012-10-31 19:02:26 +00003183/// markAllocatedVFPs - update VFPRegs according to the alignment and
3184/// number of VFP registers (unit is S register) requested.
3185static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3186 unsigned Alignment,
3187 unsigned NumRequired) {
3188 // Early Exit.
3189 if (AllocatedVFP >= 16)
3190 return;
3191 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3192 // VFP registers of the appropriate type unallocated then the argument is
3193 // allocated to the lowest-numbered sequence of such registers.
3194 for (unsigned I = 0; I < 16; I += Alignment) {
3195 bool FoundSlot = true;
3196 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3197 if (J >= 16 || VFPRegs[J]) {
3198 FoundSlot = false;
3199 break;
3200 }
3201 if (FoundSlot) {
3202 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3203 VFPRegs[J] = 1;
3204 AllocatedVFP += NumRequired;
3205 return;
3206 }
3207 }
3208 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3209 // unallocated are marked as unavailable.
3210 for (unsigned I = 0; I < 16; I++)
3211 VFPRegs[I] = 1;
3212 AllocatedVFP = 17; // We do not have enough VFP registers.
3213}
3214
3215ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3216 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003217 bool &IsHA) const {
3218 // We update number of allocated VFPs according to
3219 // 6.1.2.1 The following argument types are VFP CPRCs:
3220 // A single-precision floating-point type (including promoted
3221 // half-precision types); A double-precision floating-point type;
3222 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3223 // with a Base Type of a single- or double-precision floating-point type,
3224 // 64-bit containerized vectors or 128-bit containerized vectors with one
3225 // to four Elements.
3226
Manman Ren97f81572012-10-16 19:18:39 +00003227 // Handle illegal vector types here.
3228 if (isIllegalVectorType(Ty)) {
3229 uint64_t Size = getContext().getTypeSize(Ty);
3230 if (Size <= 32) {
3231 llvm::Type *ResType =
3232 llvm::Type::getInt32Ty(getVMContext());
3233 return ABIArgInfo::getDirect(ResType);
3234 }
3235 if (Size == 64) {
3236 llvm::Type *ResType = llvm::VectorType::get(
3237 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Ren710c5172012-10-31 19:02:26 +00003238 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren97f81572012-10-16 19:18:39 +00003239 return ABIArgInfo::getDirect(ResType);
3240 }
3241 if (Size == 128) {
3242 llvm::Type *ResType = llvm::VectorType::get(
3243 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Ren710c5172012-10-31 19:02:26 +00003244 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Ren97f81572012-10-16 19:18:39 +00003245 return ABIArgInfo::getDirect(ResType);
3246 }
3247 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3248 }
Manman Ren710c5172012-10-31 19:02:26 +00003249 // Update VFPRegs for legal vector types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003250 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3251 uint64_t Size = getContext().getTypeSize(VT);
3252 // Size of a legal vector should be power of 2 and above 64.
Manman Ren710c5172012-10-31 19:02:26 +00003253 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Renb3fa55f2012-10-30 23:21:41 +00003254 }
Manman Ren710c5172012-10-31 19:02:26 +00003255 // Update VFPRegs for floating point types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003256 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3257 if (BT->getKind() == BuiltinType::Half ||
3258 BT->getKind() == BuiltinType::Float)
Manman Ren710c5172012-10-31 19:02:26 +00003259 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Renb3fa55f2012-10-30 23:21:41 +00003260 if (BT->getKind() == BuiltinType::Double ||
Manman Ren710c5172012-10-31 19:02:26 +00003261 BT->getKind() == BuiltinType::LongDouble)
3262 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003263 }
Manman Ren97f81572012-10-16 19:18:39 +00003264
John McCalld608cdb2010-08-22 10:59:02 +00003265 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003266 // Treat an enum type as its underlying type.
3267 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3268 Ty = EnumTy->getDecl()->getIntegerType();
3269
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003270 return (Ty->isPromotableIntegerType() ?
3271 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003272 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003273
Daniel Dunbar42025572009-09-14 21:54:03 +00003274 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003275 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00003276 return ABIArgInfo::getIgnore();
3277
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003278 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
3279 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003280
Bob Wilson194f06a2011-08-03 05:58:22 +00003281 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Renb3fa55f2012-10-30 23:21:41 +00003282 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3283 // into VFP registers.
Bob Wilson194f06a2011-08-03 05:58:22 +00003284 const Type *Base = 0;
Manman Renb3fa55f2012-10-30 23:21:41 +00003285 uint64_t Members = 0;
3286 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003287 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00003288 // Base can be a floating-point or a vector.
3289 if (Base->isVectorType()) {
3290 // ElementSize is in number of floats.
3291 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Rencb489dd2012-11-06 19:05:29 +00003292 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3293 Members * ElementSize);
Manman Renb3fa55f2012-10-30 23:21:41 +00003294 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Ren710c5172012-10-31 19:02:26 +00003295 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Renb3fa55f2012-10-30 23:21:41 +00003296 else {
3297 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3298 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Ren710c5172012-10-31 19:02:26 +00003299 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003300 }
3301 IsHA = true;
Bob Wilson194f06a2011-08-03 05:58:22 +00003302 return ABIArgInfo::getExpand();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003303 }
Bob Wilson194f06a2011-08-03 05:58:22 +00003304 }
3305
Manman Ren634b3d22012-08-13 21:23:55 +00003306 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00003307 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3308 // most 8-byte. We realign the indirect argument if type alignment is bigger
3309 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00003310 uint64_t ABIAlign = 4;
3311 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3312 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3313 getABIKind() == ARMABIInfo::AAPCS)
3314 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00003315 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3316 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00003317 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00003318 }
3319
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00003320 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003321 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003322 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00003323 // FIXME: Try to match the types of the arguments more accurately where
3324 // we can.
3325 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00003326 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3327 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren78eb76e2012-06-25 22:04:00 +00003328 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00003329 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3330 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastings67d097e2011-04-27 17:24:02 +00003331 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003332
Chris Lattner9cbe4f02011-07-09 17:41:47 +00003333 llvm::Type *STy =
Chris Lattner7650d952011-06-18 22:49:11 +00003334 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003335 return ABIArgInfo::getDirect(STy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003336}
3337
Chris Lattnera3c109b2010-07-29 02:16:43 +00003338static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00003339 llvm::LLVMContext &VMContext) {
3340 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3341 // is called integer-like if its size is less than or equal to one word, and
3342 // the offset of each of its addressable sub-fields is zero.
3343
3344 uint64_t Size = Context.getTypeSize(Ty);
3345
3346 // Check that the type fits in a word.
3347 if (Size > 32)
3348 return false;
3349
3350 // FIXME: Handle vector types!
3351 if (Ty->isVectorType())
3352 return false;
3353
Daniel Dunbarb0d58192009-09-14 02:20:34 +00003354 // Float types are never treated as "integer like".
3355 if (Ty->isRealFloatingType())
3356 return false;
3357
Daniel Dunbar98303b92009-09-13 08:03:58 +00003358 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00003359 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00003360 return true;
3361
Daniel Dunbar45815812010-02-01 23:31:26 +00003362 // Small complex integer types are "integer like".
3363 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3364 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003365
3366 // Single element and zero sized arrays should be allowed, by the definition
3367 // above, but they are not.
3368
3369 // Otherwise, it must be a record type.
3370 const RecordType *RT = Ty->getAs<RecordType>();
3371 if (!RT) return false;
3372
3373 // Ignore records with flexible arrays.
3374 const RecordDecl *RD = RT->getDecl();
3375 if (RD->hasFlexibleArrayMember())
3376 return false;
3377
3378 // Check that all sub-fields are at offset 0, and are themselves "integer
3379 // like".
3380 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3381
3382 bool HadField = false;
3383 unsigned idx = 0;
3384 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3385 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00003386 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003387
Daniel Dunbar679855a2010-01-29 03:22:29 +00003388 // Bit-fields are not addressable, we only need to verify they are "integer
3389 // like". We still have to disallow a subsequent non-bitfield, for example:
3390 // struct { int : 0; int x }
3391 // is non-integer like according to gcc.
3392 if (FD->isBitField()) {
3393 if (!RD->isUnion())
3394 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003395
Daniel Dunbar679855a2010-01-29 03:22:29 +00003396 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3397 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003398
Daniel Dunbar679855a2010-01-29 03:22:29 +00003399 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003400 }
3401
Daniel Dunbar679855a2010-01-29 03:22:29 +00003402 // Check if this field is at offset 0.
3403 if (Layout.getFieldOffset(idx) != 0)
3404 return false;
3405
Daniel Dunbar98303b92009-09-13 08:03:58 +00003406 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3407 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003408
Daniel Dunbar679855a2010-01-29 03:22:29 +00003409 // Only allow at most one field in a structure. This doesn't match the
3410 // wording above, but follows gcc in situations with a field following an
3411 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00003412 if (!RD->isUnion()) {
3413 if (HadField)
3414 return false;
3415
3416 HadField = true;
3417 }
3418 }
3419
3420 return true;
3421}
3422
Chris Lattnera3c109b2010-07-29 02:16:43 +00003423ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003424 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003425 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00003426
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00003427 // Large vector types should be returned via memory.
3428 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3429 return ABIArgInfo::getIndirect(0);
3430
John McCalld608cdb2010-08-22 10:59:02 +00003431 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003432 // Treat an enum type as its underlying type.
3433 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3434 RetTy = EnumTy->getDecl()->getIntegerType();
3435
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003436 return (RetTy->isPromotableIntegerType() ?
3437 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003438 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003439
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003440 // Structures with either a non-trivial destructor or a non-trivial
3441 // copy constructor are always indirect.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003442 if (isRecordReturnIndirect(RetTy, CGT))
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003443 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3444
Daniel Dunbar98303b92009-09-13 08:03:58 +00003445 // Are we following APCS?
3446 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00003447 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00003448 return ABIArgInfo::getIgnore();
3449
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003450 // Complex types are all returned as packed integers.
3451 //
3452 // FIXME: Consider using 2 x vector types if the back end handles them
3453 // correctly.
3454 if (RetTy->isAnyComplexType())
Chris Lattner800588f2010-07-29 06:26:06 +00003455 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +00003456 getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003457
Daniel Dunbar98303b92009-09-13 08:03:58 +00003458 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003459 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003460 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003461 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003462 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003463 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003464 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003465 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3466 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003467 }
3468
3469 // Otherwise return in memory.
3470 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003471 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003472
3473 // Otherwise this is an AAPCS variant.
3474
Chris Lattnera3c109b2010-07-29 02:16:43 +00003475 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00003476 return ABIArgInfo::getIgnore();
3477
Bob Wilson3b694fa2011-11-02 04:51:36 +00003478 // Check for homogeneous aggregates with AAPCS-VFP.
3479 if (getABIKind() == AAPCS_VFP) {
3480 const Type *Base = 0;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003481 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3482 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00003483 // Homogeneous Aggregates are returned directly.
3484 return ABIArgInfo::getDirect();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003485 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00003486 }
3487
Daniel Dunbar98303b92009-09-13 08:03:58 +00003488 // Aggregates <= 4 bytes are returned in r0; other aggregates
3489 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003490 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00003491 if (Size <= 32) {
3492 // Return in the smallest viable integer type.
3493 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003494 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003495 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003496 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3497 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003498 }
3499
Daniel Dunbar98303b92009-09-13 08:03:58 +00003500 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003501}
3502
Manman Ren97f81572012-10-16 19:18:39 +00003503/// isIllegalVector - check whether Ty is an illegal vector type.
3504bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3505 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3506 // Check whether VT is legal.
3507 unsigned NumElements = VT->getNumElements();
3508 uint64_t Size = getContext().getTypeSize(VT);
3509 // NumElements should be power of 2.
3510 if ((NumElements & (NumElements - 1)) != 0)
3511 return true;
3512 // Size should be greater than 32 bits.
3513 return Size <= 32;
3514 }
3515 return false;
3516}
3517
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003518llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00003519 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003520 llvm::Type *BP = CGF.Int8PtrTy;
3521 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003522
3523 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00003524 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003525 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00003526
3527 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00003528 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00003529 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00003530
3531 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3532 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00003533 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3534 getABIKind() == ARMABIInfo::AAPCS)
3535 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3536 else
3537 TyAlign = 4;
Manman Ren97f81572012-10-16 19:18:39 +00003538 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3539 if (isIllegalVectorType(Ty) && Size > 16) {
3540 IsIndirect = true;
3541 Size = 4;
3542 TyAlign = 4;
3543 }
Manman Rend105e732012-10-16 19:01:37 +00003544
3545 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00003546 if (TyAlign > 4) {
3547 assert((TyAlign & (TyAlign - 1)) == 0 &&
3548 "Alignment is not power of 2!");
3549 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3550 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3551 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00003552 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00003553 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003554
3555 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00003556 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003557 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00003558 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003559 "ap.next");
3560 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3561
Manman Ren97f81572012-10-16 19:18:39 +00003562 if (IsIndirect)
3563 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00003564 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00003565 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3566 // may not be correctly aligned for the vector type. We create an aligned
3567 // temporary space and copy the content over from ap.cur to the temporary
3568 // space. This is necessary if the natural alignment of the type is greater
3569 // than the ABI alignment.
3570 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3571 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3572 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3573 "var.align");
3574 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3575 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3576 Builder.CreateMemCpy(Dst, Src,
3577 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3578 TyAlign, false);
3579 Addr = AlignedTemp; //The content is in aligned location.
3580 }
3581 llvm::Type *PTy =
3582 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3583 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3584
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003585 return AddrTyped;
3586}
3587
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003588namespace {
3589
Derek Schuff263366f2012-10-16 22:30:41 +00003590class NaClARMABIInfo : public ABIInfo {
3591 public:
3592 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3593 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3594 virtual void computeInfo(CGFunctionInfo &FI) const;
3595 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3596 CodeGenFunction &CGF) const;
3597 private:
3598 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3599 ARMABIInfo NInfo; // Used for everything else.
3600};
3601
3602class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3603 public:
3604 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3605 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3606};
3607
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003608}
3609
Derek Schuff263366f2012-10-16 22:30:41 +00003610void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3611 if (FI.getASTCallingConvention() == CC_PnaclCall)
3612 PInfo.computeInfo(FI);
3613 else
3614 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3615}
3616
3617llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3618 CodeGenFunction &CGF) const {
3619 // Always use the native convention; calling pnacl-style varargs functions
3620 // is unsupported.
3621 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3622}
3623
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003624//===----------------------------------------------------------------------===//
Tim Northoverc264e162013-01-31 12:13:10 +00003625// AArch64 ABI Implementation
3626//===----------------------------------------------------------------------===//
3627
3628namespace {
3629
3630class AArch64ABIInfo : public ABIInfo {
3631public:
3632 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3633
3634private:
3635 // The AArch64 PCS is explicit about return types and argument types being
3636 // handled identically, so we don't need to draw a distinction between
3637 // Argument and Return classification.
3638 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3639 int &FreeVFPRegs) const;
3640
3641 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3642 llvm::Type *DirectTy = 0) const;
3643
3644 virtual void computeInfo(CGFunctionInfo &FI) const;
3645
3646 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3647 CodeGenFunction &CGF) const;
3648};
3649
3650class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3651public:
3652 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3653 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3654
3655 const AArch64ABIInfo &getABIInfo() const {
3656 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3657 }
3658
3659 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3660 return 31;
3661 }
3662
3663 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3664 llvm::Value *Address) const {
3665 // 0-31 are x0-x30 and sp: 8 bytes each
3666 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3667 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3668
3669 // 64-95 are v0-v31: 16 bytes each
3670 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3671 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3672
3673 return false;
3674 }
3675
3676};
3677
3678}
3679
3680void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3681 int FreeIntRegs = 8, FreeVFPRegs = 8;
3682
3683 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3684 FreeIntRegs, FreeVFPRegs);
3685
3686 FreeIntRegs = FreeVFPRegs = 8;
3687 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3688 it != ie; ++it) {
3689 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3690
3691 }
3692}
3693
3694ABIArgInfo
3695AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3696 bool IsInt, llvm::Type *DirectTy) const {
3697 if (FreeRegs >= RegsNeeded) {
3698 FreeRegs -= RegsNeeded;
3699 return ABIArgInfo::getDirect(DirectTy);
3700 }
3701
3702 llvm::Type *Padding = 0;
3703
3704 // We need padding so that later arguments don't get filled in anyway. That
3705 // wouldn't happen if only ByVal arguments followed in the same category, but
3706 // a large structure will simply seem to be a pointer as far as LLVM is
3707 // concerned.
3708 if (FreeRegs > 0) {
3709 if (IsInt)
3710 Padding = llvm::Type::getInt64Ty(getVMContext());
3711 else
3712 Padding = llvm::Type::getFloatTy(getVMContext());
3713
3714 // Either [N x i64] or [N x float].
3715 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3716 FreeRegs = 0;
3717 }
3718
3719 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3720 /*IsByVal=*/ true, /*Realign=*/ false,
3721 Padding);
3722}
3723
3724
3725ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3726 int &FreeIntRegs,
3727 int &FreeVFPRegs) const {
3728 // Can only occurs for return, but harmless otherwise.
3729 if (Ty->isVoidType())
3730 return ABIArgInfo::getIgnore();
3731
3732 // Large vector types should be returned via memory. There's no such concept
3733 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3734 // classified they'd go into memory (see B.3).
3735 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3736 if (FreeIntRegs > 0)
3737 --FreeIntRegs;
3738 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3739 }
3740
3741 // All non-aggregate LLVM types have a concrete ABI representation so they can
3742 // be passed directly. After this block we're guaranteed to be in a
3743 // complicated case.
3744 if (!isAggregateTypeForABI(Ty)) {
3745 // Treat an enum type as its underlying type.
3746 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3747 Ty = EnumTy->getDecl()->getIntegerType();
3748
3749 if (Ty->isFloatingType() || Ty->isVectorType())
3750 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3751
3752 assert(getContext().getTypeSize(Ty) <= 128 &&
3753 "unexpectedly large scalar type");
3754
3755 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3756
3757 // If the type may need padding registers to ensure "alignment", we must be
3758 // careful when this is accounted for. Increasing the effective size covers
3759 // all cases.
3760 if (getContext().getTypeAlign(Ty) == 128)
3761 RegsNeeded += FreeIntRegs % 2 != 0;
3762
3763 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3764 }
3765
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003766 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
3767 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northoverc264e162013-01-31 12:13:10 +00003768 --FreeIntRegs;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003769 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northoverc264e162013-01-31 12:13:10 +00003770 }
3771
3772 if (isEmptyRecord(getContext(), Ty, true)) {
3773 if (!getContext().getLangOpts().CPlusPlus) {
3774 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3775 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3776 // the object for parameter-passsing purposes.
3777 return ABIArgInfo::getIgnore();
3778 }
3779
3780 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3781 // description of va_arg in the PCS require that an empty struct does
3782 // actually occupy space for parameter-passing. I'm hoping for a
3783 // clarification giving an explicit paragraph to point to in future.
3784 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3785 llvm::Type::getInt8Ty(getVMContext()));
3786 }
3787
3788 // Homogeneous vector aggregates get passed in registers or on the stack.
3789 const Type *Base = 0;
3790 uint64_t NumMembers = 0;
3791 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3792 assert(Base && "Base class should be set for homogeneous aggregate");
3793 // Homogeneous aggregates are passed and returned directly.
3794 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3795 /*IsInt=*/ false);
3796 }
3797
3798 uint64_t Size = getContext().getTypeSize(Ty);
3799 if (Size <= 128) {
3800 // Small structs can use the same direct type whether they're in registers
3801 // or on the stack.
3802 llvm::Type *BaseTy;
3803 unsigned NumBases;
3804 int SizeInRegs = (Size + 63) / 64;
3805
3806 if (getContext().getTypeAlign(Ty) == 128) {
3807 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3808 NumBases = 1;
3809
3810 // If the type may need padding registers to ensure "alignment", we must
3811 // be careful when this is accounted for. Increasing the effective size
3812 // covers all cases.
3813 SizeInRegs += FreeIntRegs % 2 != 0;
3814 } else {
3815 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3816 NumBases = SizeInRegs;
3817 }
3818 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3819
3820 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3821 /*IsInt=*/ true, DirectTy);
3822 }
3823
3824 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3825 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3826 --FreeIntRegs;
3827 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3828}
3829
3830llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3831 CodeGenFunction &CGF) const {
3832 // The AArch64 va_list type and handling is specified in the Procedure Call
3833 // Standard, section B.4:
3834 //
3835 // struct {
3836 // void *__stack;
3837 // void *__gr_top;
3838 // void *__vr_top;
3839 // int __gr_offs;
3840 // int __vr_offs;
3841 // };
3842
3843 assert(!CGF.CGM.getDataLayout().isBigEndian()
3844 && "va_arg not implemented for big-endian AArch64");
3845
3846 int FreeIntRegs = 8, FreeVFPRegs = 8;
3847 Ty = CGF.getContext().getCanonicalType(Ty);
3848 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3849
3850 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3851 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3852 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3853 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3854
3855 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3856 int reg_top_index;
3857 int RegSize;
3858 if (FreeIntRegs < 8) {
3859 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
3860 // 3 is the field number of __gr_offs
3861 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3862 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3863 reg_top_index = 1; // field number for __gr_top
3864 RegSize = 8 * (8 - FreeIntRegs);
3865 } else {
3866 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
3867 // 4 is the field number of __vr_offs.
3868 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3869 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3870 reg_top_index = 2; // field number for __vr_top
3871 RegSize = 16 * (8 - FreeVFPRegs);
3872 }
3873
3874 //=======================================
3875 // Find out where argument was passed
3876 //=======================================
3877
3878 // If reg_offs >= 0 we're already using the stack for this type of
3879 // argument. We don't want to keep updating reg_offs (in case it overflows,
3880 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3881 // whatever they get).
3882 llvm::Value *UsingStack = 0;
3883 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
3884 llvm::ConstantInt::get(CGF.Int32Ty, 0));
3885
3886 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3887
3888 // Otherwise, at least some kind of argument could go in these registers, the
3889 // quesiton is whether this particular type is too big.
3890 CGF.EmitBlock(MaybeRegBlock);
3891
3892 // Integer arguments may need to correct register alignment (for example a
3893 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3894 // align __gr_offs to calculate the potential address.
3895 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
3896 int Align = getContext().getTypeAlign(Ty) / 8;
3897
3898 reg_offs = CGF.Builder.CreateAdd(reg_offs,
3899 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3900 "align_regoffs");
3901 reg_offs = CGF.Builder.CreateAnd(reg_offs,
3902 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3903 "aligned_regoffs");
3904 }
3905
3906 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
3907 llvm::Value *NewOffset = 0;
3908 NewOffset = CGF.Builder.CreateAdd(reg_offs,
3909 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
3910 "new_reg_offs");
3911 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3912
3913 // Now we're in a position to decide whether this argument really was in
3914 // registers or not.
3915 llvm::Value *InRegs = 0;
3916 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
3917 llvm::ConstantInt::get(CGF.Int32Ty, 0),
3918 "inreg");
3919
3920 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3921
3922 //=======================================
3923 // Argument was in registers
3924 //=======================================
3925
3926 // Now we emit the code for if the argument was originally passed in
3927 // registers. First start the appropriate block:
3928 CGF.EmitBlock(InRegBlock);
3929
3930 llvm::Value *reg_top_p = 0, *reg_top = 0;
3931 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3932 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3933 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
3934 llvm::Value *RegAddr = 0;
3935 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3936
3937 if (!AI.isDirect()) {
3938 // If it's been passed indirectly (actually a struct), whatever we find from
3939 // stored registers or on the stack will actually be a struct **.
3940 MemTy = llvm::PointerType::getUnqual(MemTy);
3941 }
3942
3943 const Type *Base = 0;
3944 uint64_t NumMembers;
3945 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
3946 && NumMembers > 1) {
3947 // Homogeneous aggregates passed in registers will have their elements split
3948 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3949 // qN+1, ...). We reload and store into a temporary local variable
3950 // contiguously.
3951 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
3952 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3953 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3954 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3955
3956 for (unsigned i = 0; i < NumMembers; ++i) {
3957 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
3958 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3959 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
3960 llvm::PointerType::getUnqual(BaseTy));
3961 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3962
3963 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3964 CGF.Builder.CreateStore(Elem, StoreAddr);
3965 }
3966
3967 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3968 } else {
3969 // Otherwise the object is contiguous in memory
3970 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3971 }
3972
3973 CGF.EmitBranch(ContBlock);
3974
3975 //=======================================
3976 // Argument was on the stack
3977 //=======================================
3978 CGF.EmitBlock(OnStackBlock);
3979
3980 llvm::Value *stack_p = 0, *OnStackAddr = 0;
3981 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3982 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3983
3984 // Again, stack arguments may need realigmnent. In this case both integer and
3985 // floating-point ones might be affected.
3986 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
3987 int Align = getContext().getTypeAlign(Ty) / 8;
3988
3989 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3990
3991 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
3992 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3993 "align_stack");
3994 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
3995 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3996 "align_stack");
3997
3998 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3999 }
4000
4001 uint64_t StackSize;
4002 if (AI.isDirect())
4003 StackSize = getContext().getTypeSize(Ty) / 8;
4004 else
4005 StackSize = 8;
4006
4007 // All stack slots are 8 bytes
4008 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4009
4010 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4011 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4012 "new_stack");
4013
4014 // Write the new value of __stack for the next call to va_arg
4015 CGF.Builder.CreateStore(NewStack, stack_p);
4016
4017 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4018
4019 CGF.EmitBranch(ContBlock);
4020
4021 //=======================================
4022 // Tidy up
4023 //=======================================
4024 CGF.EmitBlock(ContBlock);
4025
4026 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4027 ResAddr->addIncoming(RegAddr, InRegBlock);
4028 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4029
4030 if (AI.isDirect())
4031 return ResAddr;
4032
4033 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4034}
4035
4036//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00004037// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004038//===----------------------------------------------------------------------===//
4039
4040namespace {
4041
Justin Holewinski2c585b92012-05-24 17:43:12 +00004042class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004043public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00004044 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004045
4046 ABIArgInfo classifyReturnType(QualType RetTy) const;
4047 ABIArgInfo classifyArgumentType(QualType Ty) const;
4048
4049 virtual void computeInfo(CGFunctionInfo &FI) const;
4050 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4051 CodeGenFunction &CFG) const;
4052};
4053
Justin Holewinski2c585b92012-05-24 17:43:12 +00004054class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004055public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00004056 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4057 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski818eafb2011-10-05 17:58:44 +00004058
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004059 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4060 CodeGen::CodeGenModule &M) const;
Justin Holewinskidca8f332013-03-30 14:38:24 +00004061private:
4062 static void addKernelMetadata(llvm::Function *F);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004063};
4064
Justin Holewinski2c585b92012-05-24 17:43:12 +00004065ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004066 if (RetTy->isVoidType())
4067 return ABIArgInfo::getIgnore();
4068 if (isAggregateTypeForABI(RetTy))
4069 return ABIArgInfo::getIndirect(0);
4070 return ABIArgInfo::getDirect();
4071}
4072
Justin Holewinski2c585b92012-05-24 17:43:12 +00004073ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004074 if (isAggregateTypeForABI(Ty))
4075 return ABIArgInfo::getIndirect(0);
4076
4077 return ABIArgInfo::getDirect();
4078}
4079
Justin Holewinski2c585b92012-05-24 17:43:12 +00004080void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004081 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4082 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4083 it != ie; ++it)
4084 it->info = classifyArgumentType(it->type);
4085
4086 // Always honor user-specified calling convention.
4087 if (FI.getCallingConvention() != llvm::CallingConv::C)
4088 return;
4089
John McCallbd7370a2013-02-28 19:01:20 +00004090 FI.setEffectiveCallingConvention(getRuntimeCC());
4091}
4092
Justin Holewinski2c585b92012-05-24 17:43:12 +00004093llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4094 CodeGenFunction &CFG) const {
4095 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004096}
4097
Justin Holewinski2c585b92012-05-24 17:43:12 +00004098void NVPTXTargetCodeGenInfo::
4099SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4100 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00004101 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4102 if (!FD) return;
4103
4104 llvm::Function *F = cast<llvm::Function>(GV);
4105
4106 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00004107 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004108 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004109 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004110 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004111 // OpenCL __kernel functions get kernel metadata
4112 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004113 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004114 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004115 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004116 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00004117
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004118 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00004119 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004120 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004121 // __global__ functions cannot be called from the device, we do not
4122 // need to set the noinline attribute.
4123 if (FD->getAttr<CUDAGlobalAttr>())
Justin Holewinskidca8f332013-03-30 14:38:24 +00004124 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004125 }
4126}
4127
Justin Holewinskidca8f332013-03-30 14:38:24 +00004128void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4129 llvm::Module *M = F->getParent();
4130 llvm::LLVMContext &Ctx = M->getContext();
4131
4132 // Get "nvvm.annotations" metadata node
4133 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4134
4135 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4136 llvm::SmallVector<llvm::Value *, 3> MDVals;
4137 MDVals.push_back(F);
4138 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4139 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4140
4141 // Append metadata to nvvm.annotations
4142 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4143}
4144
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004145}
4146
4147//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00004148// SystemZ ABI Implementation
4149//===----------------------------------------------------------------------===//
4150
4151namespace {
4152
4153class SystemZABIInfo : public ABIInfo {
4154public:
4155 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4156
4157 bool isPromotableIntegerType(QualType Ty) const;
4158 bool isCompoundType(QualType Ty) const;
4159 bool isFPArgumentType(QualType Ty) const;
4160
4161 ABIArgInfo classifyReturnType(QualType RetTy) const;
4162 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4163
4164 virtual void computeInfo(CGFunctionInfo &FI) const {
4165 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4166 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4167 it != ie; ++it)
4168 it->info = classifyArgumentType(it->type);
4169 }
4170
4171 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4172 CodeGenFunction &CGF) const;
4173};
4174
4175class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4176public:
4177 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4178 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4179};
4180
4181}
4182
4183bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4184 // Treat an enum type as its underlying type.
4185 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4186 Ty = EnumTy->getDecl()->getIntegerType();
4187
4188 // Promotable integer types are required to be promoted by the ABI.
4189 if (Ty->isPromotableIntegerType())
4190 return true;
4191
4192 // 32-bit values must also be promoted.
4193 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4194 switch (BT->getKind()) {
4195 case BuiltinType::Int:
4196 case BuiltinType::UInt:
4197 return true;
4198 default:
4199 return false;
4200 }
4201 return false;
4202}
4203
4204bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4205 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4206}
4207
4208bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4209 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4210 switch (BT->getKind()) {
4211 case BuiltinType::Float:
4212 case BuiltinType::Double:
4213 return true;
4214 default:
4215 return false;
4216 }
4217
4218 if (const RecordType *RT = Ty->getAsStructureType()) {
4219 const RecordDecl *RD = RT->getDecl();
4220 bool Found = false;
4221
4222 // If this is a C++ record, check the bases first.
4223 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4224 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4225 E = CXXRD->bases_end(); I != E; ++I) {
4226 QualType Base = I->getType();
4227
4228 // Empty bases don't affect things either way.
4229 if (isEmptyRecord(getContext(), Base, true))
4230 continue;
4231
4232 if (Found)
4233 return false;
4234 Found = isFPArgumentType(Base);
4235 if (!Found)
4236 return false;
4237 }
4238
4239 // Check the fields.
4240 for (RecordDecl::field_iterator I = RD->field_begin(),
4241 E = RD->field_end(); I != E; ++I) {
4242 const FieldDecl *FD = *I;
4243
4244 // Empty bitfields don't affect things either way.
4245 // Unlike isSingleElementStruct(), empty structure and array fields
4246 // do count. So do anonymous bitfields that aren't zero-sized.
4247 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4248 return true;
4249
4250 // Unlike isSingleElementStruct(), arrays do not count.
4251 // Nested isFPArgumentType structures still do though.
4252 if (Found)
4253 return false;
4254 Found = isFPArgumentType(FD->getType());
4255 if (!Found)
4256 return false;
4257 }
4258
4259 // Unlike isSingleElementStruct(), trailing padding is allowed.
4260 // An 8-byte aligned struct s { float f; } is passed as a double.
4261 return Found;
4262 }
4263
4264 return false;
4265}
4266
4267llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4268 CodeGenFunction &CGF) const {
4269 // Assume that va_list type is correct; should be pointer to LLVM type:
4270 // struct {
4271 // i64 __gpr;
4272 // i64 __fpr;
4273 // i8 *__overflow_arg_area;
4274 // i8 *__reg_save_area;
4275 // };
4276
4277 // Every argument occupies 8 bytes and is passed by preference in either
4278 // GPRs or FPRs.
4279 Ty = CGF.getContext().getCanonicalType(Ty);
4280 ABIArgInfo AI = classifyArgumentType(Ty);
4281 bool InFPRs = isFPArgumentType(Ty);
4282
4283 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4284 bool IsIndirect = AI.isIndirect();
4285 unsigned UnpaddedBitSize;
4286 if (IsIndirect) {
4287 APTy = llvm::PointerType::getUnqual(APTy);
4288 UnpaddedBitSize = 64;
4289 } else
4290 UnpaddedBitSize = getContext().getTypeSize(Ty);
4291 unsigned PaddedBitSize = 64;
4292 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4293
4294 unsigned PaddedSize = PaddedBitSize / 8;
4295 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4296
4297 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4298 if (InFPRs) {
4299 MaxRegs = 4; // Maximum of 4 FPR arguments
4300 RegCountField = 1; // __fpr
4301 RegSaveIndex = 16; // save offset for f0
4302 RegPadding = 0; // floats are passed in the high bits of an FPR
4303 } else {
4304 MaxRegs = 5; // Maximum of 5 GPR arguments
4305 RegCountField = 0; // __gpr
4306 RegSaveIndex = 2; // save offset for r2
4307 RegPadding = Padding; // values are passed in the low bits of a GPR
4308 }
4309
4310 llvm::Value *RegCountPtr =
4311 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4312 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4313 llvm::Type *IndexTy = RegCount->getType();
4314 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4315 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4316 "fits_in_regs");
4317
4318 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4319 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4320 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4321 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4322
4323 // Emit code to load the value if it was passed in registers.
4324 CGF.EmitBlock(InRegBlock);
4325
4326 // Work out the address of an argument register.
4327 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4328 llvm::Value *ScaledRegCount =
4329 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4330 llvm::Value *RegBase =
4331 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4332 llvm::Value *RegOffset =
4333 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4334 llvm::Value *RegSaveAreaPtr =
4335 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4336 llvm::Value *RegSaveArea =
4337 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4338 llvm::Value *RawRegAddr =
4339 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4340 llvm::Value *RegAddr =
4341 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4342
4343 // Update the register count
4344 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4345 llvm::Value *NewRegCount =
4346 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4347 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4348 CGF.EmitBranch(ContBlock);
4349
4350 // Emit code to load the value if it was passed in memory.
4351 CGF.EmitBlock(InMemBlock);
4352
4353 // Work out the address of a stack argument.
4354 llvm::Value *OverflowArgAreaPtr =
4355 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4356 llvm::Value *OverflowArgArea =
4357 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4358 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4359 llvm::Value *RawMemAddr =
4360 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4361 llvm::Value *MemAddr =
4362 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4363
4364 // Update overflow_arg_area_ptr pointer
4365 llvm::Value *NewOverflowArgArea =
4366 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4367 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4368 CGF.EmitBranch(ContBlock);
4369
4370 // Return the appropriate result.
4371 CGF.EmitBlock(ContBlock);
4372 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4373 ResAddr->addIncoming(RegAddr, InRegBlock);
4374 ResAddr->addIncoming(MemAddr, InMemBlock);
4375
4376 if (IsIndirect)
4377 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4378
4379 return ResAddr;
4380}
4381
4382
4383ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4384 if (RetTy->isVoidType())
4385 return ABIArgInfo::getIgnore();
4386 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4387 return ABIArgInfo::getIndirect(0);
4388 return (isPromotableIntegerType(RetTy) ?
4389 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4390}
4391
4392ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4393 // Handle the generic C++ ABI.
4394 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
4395 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4396
4397 // Integers and enums are extended to full register width.
4398 if (isPromotableIntegerType(Ty))
4399 return ABIArgInfo::getExtend();
4400
4401 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4402 uint64_t Size = getContext().getTypeSize(Ty);
4403 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
4404 return ABIArgInfo::getIndirect(0);
4405
4406 // Handle small structures.
4407 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4408 // Structures with flexible arrays have variable length, so really
4409 // fail the size test above.
4410 const RecordDecl *RD = RT->getDecl();
4411 if (RD->hasFlexibleArrayMember())
4412 return ABIArgInfo::getIndirect(0);
4413
4414 // The structure is passed as an unextended integer, a float, or a double.
4415 llvm::Type *PassTy;
4416 if (isFPArgumentType(Ty)) {
4417 assert(Size == 32 || Size == 64);
4418 if (Size == 32)
4419 PassTy = llvm::Type::getFloatTy(getVMContext());
4420 else
4421 PassTy = llvm::Type::getDoubleTy(getVMContext());
4422 } else
4423 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4424 return ABIArgInfo::getDirect(PassTy);
4425 }
4426
4427 // Non-structure compounds are passed indirectly.
4428 if (isCompoundType(Ty))
4429 return ABIArgInfo::getIndirect(0);
4430
4431 return ABIArgInfo::getDirect(0);
4432}
4433
4434//===----------------------------------------------------------------------===//
Wesley Peck276fdf42010-12-19 19:57:51 +00004435// MBlaze ABI Implementation
4436//===----------------------------------------------------------------------===//
4437
4438namespace {
4439
4440class MBlazeABIInfo : public ABIInfo {
4441public:
4442 MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4443
4444 bool isPromotableIntegerType(QualType Ty) const;
4445
4446 ABIArgInfo classifyReturnType(QualType RetTy) const;
4447 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4448
4449 virtual void computeInfo(CGFunctionInfo &FI) const {
4450 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4451 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4452 it != ie; ++it)
4453 it->info = classifyArgumentType(it->type);
4454 }
4455
4456 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4457 CodeGenFunction &CGF) const;
4458};
4459
4460class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo {
4461public:
4462 MBlazeTargetCodeGenInfo(CodeGenTypes &CGT)
4463 : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {}
4464 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4465 CodeGen::CodeGenModule &M) const;
4466};
4467
4468}
4469
4470bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const {
4471 // MBlaze ABI requires all 8 and 16 bit quantities to be extended.
4472 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4473 switch (BT->getKind()) {
4474 case BuiltinType::Bool:
4475 case BuiltinType::Char_S:
4476 case BuiltinType::Char_U:
4477 case BuiltinType::SChar:
4478 case BuiltinType::UChar:
4479 case BuiltinType::Short:
4480 case BuiltinType::UShort:
4481 return true;
4482 default:
4483 return false;
4484 }
4485 return false;
4486}
4487
4488llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4489 CodeGenFunction &CGF) const {
4490 // FIXME: Implement
4491 return 0;
4492}
4493
4494
4495ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const {
4496 if (RetTy->isVoidType())
4497 return ABIArgInfo::getIgnore();
4498 if (isAggregateTypeForABI(RetTy))
4499 return ABIArgInfo::getIndirect(0);
4500
4501 return (isPromotableIntegerType(RetTy) ?
4502 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4503}
4504
4505ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const {
4506 if (isAggregateTypeForABI(Ty))
4507 return ABIArgInfo::getIndirect(0);
4508
4509 return (isPromotableIntegerType(Ty) ?
4510 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4511}
4512
4513void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4514 llvm::GlobalValue *GV,
4515 CodeGen::CodeGenModule &M)
4516 const {
4517 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4518 if (!FD) return;
NAKAMURA Takumi125b4cb2011-02-17 08:50:50 +00004519
Wesley Peck276fdf42010-12-19 19:57:51 +00004520 llvm::CallingConv::ID CC = llvm::CallingConv::C;
4521 if (FD->hasAttr<MBlazeInterruptHandlerAttr>())
4522 CC = llvm::CallingConv::MBLAZE_INTR;
4523 else if (FD->hasAttr<MBlazeSaveVolatilesAttr>())
4524 CC = llvm::CallingConv::MBLAZE_SVOL;
4525
4526 if (CC != llvm::CallingConv::C) {
4527 // Handle 'interrupt_handler' attribute:
4528 llvm::Function *F = cast<llvm::Function>(GV);
4529
4530 // Step 1: Set ISR calling convention.
4531 F->setCallingConv(CC);
4532
4533 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00004534 F->addFnAttr(llvm::Attribute::NoInline);
Wesley Peck276fdf42010-12-19 19:57:51 +00004535 }
4536
4537 // Step 3: Emit _interrupt_handler alias.
4538 if (CC == llvm::CallingConv::MBLAZE_INTR)
4539 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
4540 "_interrupt_handler", GV, &M.getModule());
4541}
4542
4543
4544//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004545// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004546//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004547
4548namespace {
4549
4550class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4551public:
Chris Lattnerea044322010-07-29 02:01:43 +00004552 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4553 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004554 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4555 CodeGen::CodeGenModule &M) const;
4556};
4557
4558}
4559
4560void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4561 llvm::GlobalValue *GV,
4562 CodeGen::CodeGenModule &M) const {
4563 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4564 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4565 // Handle 'interrupt' attribute:
4566 llvm::Function *F = cast<llvm::Function>(GV);
4567
4568 // Step 1: Set ISR calling convention.
4569 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4570
4571 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00004572 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004573
4574 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004575 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004576 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004577 "__isr_" + Twine(Num),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004578 GV, &M.getModule());
4579 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004580 }
4581}
4582
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004583//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00004584// MIPS ABI Implementation. This works for both little-endian and
4585// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004586//===----------------------------------------------------------------------===//
4587
John McCallaeeb7012010-05-27 06:19:26 +00004588namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004589class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004590 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00004591 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4592 void CoerceToIntArgs(uint64_t TySize,
4593 SmallVector<llvm::Type*, 8> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004594 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004595 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004596 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004597public:
Akira Hatanakab551dd32011-11-03 00:05:50 +00004598 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakac359f202012-07-03 19:24:06 +00004599 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
4600 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00004601
4602 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004603 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004604 virtual void computeInfo(CGFunctionInfo &FI) const;
4605 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4606 CodeGenFunction &CGF) const;
4607};
4608
John McCallaeeb7012010-05-27 06:19:26 +00004609class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004610 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00004611public:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004612 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4613 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
4614 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00004615
4616 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4617 return 29;
4618 }
4619
Reed Kotler7dfd1822013-01-16 17:10:28 +00004620 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4621 CodeGen::CodeGenModule &CGM) const {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004622 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4623 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00004624 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004625 if (FD->hasAttr<Mips16Attr>()) {
4626 Fn->addFnAttr("mips16");
4627 }
4628 else if (FD->hasAttr<NoMips16Attr>()) {
4629 Fn->addFnAttr("nomips16");
4630 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00004631 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004632
John McCallaeeb7012010-05-27 06:19:26 +00004633 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004634 llvm::Value *Address) const;
John McCall49e34be2011-08-30 01:42:09 +00004635
4636 unsigned getSizeOfUnwindException() const {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004637 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00004638 }
John McCallaeeb7012010-05-27 06:19:26 +00004639};
4640}
4641
Akira Hatanakac359f202012-07-03 19:24:06 +00004642void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
4643 SmallVector<llvm::Type*, 8> &ArgList) const {
4644 llvm::IntegerType *IntTy =
4645 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004646
4647 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4648 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4649 ArgList.push_back(IntTy);
4650
4651 // If necessary, add one more integer type to ArgList.
4652 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4653
4654 if (R)
4655 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004656}
4657
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004658// In N32/64, an aligned double precision floating point field is passed in
4659// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004660llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00004661 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4662
4663 if (IsO32) {
4664 CoerceToIntArgs(TySize, ArgList);
4665 return llvm::StructType::get(getVMContext(), ArgList);
4666 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004667
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00004668 if (Ty->isComplexType())
4669 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00004670
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004671 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004672
Akira Hatanakac359f202012-07-03 19:24:06 +00004673 // Unions/vectors are passed in integer registers.
4674 if (!RT || !RT->isStructureOrClassType()) {
4675 CoerceToIntArgs(TySize, ArgList);
4676 return llvm::StructType::get(getVMContext(), ArgList);
4677 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004678
4679 const RecordDecl *RD = RT->getDecl();
4680 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004681 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004682
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004683 uint64_t LastOffset = 0;
4684 unsigned idx = 0;
4685 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4686
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004687 // Iterate over fields in the struct/class and check if there are any aligned
4688 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004689 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4690 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00004691 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004692 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4693
4694 if (!BT || BT->getKind() != BuiltinType::Double)
4695 continue;
4696
4697 uint64_t Offset = Layout.getFieldOffset(idx);
4698 if (Offset % 64) // Ignore doubles that are not aligned.
4699 continue;
4700
4701 // Add ((Offset - LastOffset) / 64) args of type i64.
4702 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4703 ArgList.push_back(I64);
4704
4705 // Add double type.
4706 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4707 LastOffset = Offset + 64;
4708 }
4709
Akira Hatanakac359f202012-07-03 19:24:06 +00004710 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4711 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004712
4713 return llvm::StructType::get(getVMContext(), ArgList);
4714}
4715
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004716llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004717 assert((Offset % MinABIStackAlignInBytes) == 0);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004718
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004719 if ((Align - 1) & Offset)
4720 return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
4721
4722 return 0;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004723}
Akira Hatanaka9659d592012-01-10 22:44:52 +00004724
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004725ABIArgInfo
4726MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004727 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004728 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004729 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004730
Akira Hatanakac359f202012-07-03 19:24:06 +00004731 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4732 (uint64_t)StackAlignInBytes);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004733 Offset = llvm::RoundUpToAlignment(Offset, Align);
4734 Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004735
Akira Hatanakac359f202012-07-03 19:24:06 +00004736 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004737 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004738 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004739 return ABIArgInfo::getIgnore();
4740
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004741 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004742 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004743 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004744 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00004745
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004746 // If we have reached here, aggregates are passed directly by coercing to
4747 // another structure type. Padding is inserted if the offset of the
4748 // aggregate is unaligned.
4749 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
4750 getPaddingType(Align, OrigOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004751 }
4752
4753 // Treat an enum type as its underlying type.
4754 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4755 Ty = EnumTy->getDecl()->getIntegerType();
4756
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004757 if (Ty->isPromotableIntegerType())
4758 return ABIArgInfo::getExtend();
4759
Akira Hatanaka4055cfc2013-01-24 21:47:33 +00004760 return ABIArgInfo::getDirect(0, 0,
4761 IsO32 ? 0 : getPaddingType(Align, OrigOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004762}
4763
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004764llvm::Type*
4765MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00004766 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00004767 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004768
Akira Hatanakada54ff32012-02-09 18:49:26 +00004769 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004770 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00004771 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4772 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004773
Akira Hatanakada54ff32012-02-09 18:49:26 +00004774 // N32/64 returns struct/classes in floating point registers if the
4775 // following conditions are met:
4776 // 1. The size of the struct/class is no larger than 128-bit.
4777 // 2. The struct/class has one or two fields all of which are floating
4778 // point types.
4779 // 3. The offset of the first field is zero (this follows what gcc does).
4780 //
4781 // Any other composite results are returned in integer registers.
4782 //
4783 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4784 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4785 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00004786 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004787
Akira Hatanakada54ff32012-02-09 18:49:26 +00004788 if (!BT || !BT->isFloatingPoint())
4789 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004790
David Blaikie262bc182012-04-30 02:36:29 +00004791 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00004792 }
4793
4794 if (b == e)
4795 return llvm::StructType::get(getVMContext(), RTList,
4796 RD->hasAttr<PackedAttr>());
4797
4798 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004799 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004800 }
4801
Akira Hatanakac359f202012-07-03 19:24:06 +00004802 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004803 return llvm::StructType::get(getVMContext(), RTList);
4804}
4805
Akira Hatanaka619e8872011-06-02 00:09:17 +00004806ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00004807 uint64_t Size = getContext().getTypeSize(RetTy);
4808
4809 if (RetTy->isVoidType() || Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004810 return ABIArgInfo::getIgnore();
4811
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00004812 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004813 if (isRecordReturnIndirect(RetTy, CGT))
4814 return ABIArgInfo::getIndirect(0);
4815
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004816 if (Size <= 128) {
4817 if (RetTy->isAnyComplexType())
4818 return ABIArgInfo::getDirect();
4819
Akira Hatanakac359f202012-07-03 19:24:06 +00004820 // O32 returns integer vectors in registers.
4821 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4822 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4823
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004824 if (!IsO32)
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004825 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4826 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00004827
4828 return ABIArgInfo::getIndirect(0);
4829 }
4830
4831 // Treat an enum type as its underlying type.
4832 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4833 RetTy = EnumTy->getDecl()->getIntegerType();
4834
4835 return (RetTy->isPromotableIntegerType() ?
4836 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4837}
4838
4839void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00004840 ABIArgInfo &RetInfo = FI.getReturnInfo();
4841 RetInfo = classifyReturnType(FI.getReturnType());
4842
4843 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004844 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00004845
Akira Hatanaka619e8872011-06-02 00:09:17 +00004846 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4847 it != ie; ++it)
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004848 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00004849}
4850
4851llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4852 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00004853 llvm::Type *BP = CGF.Int8PtrTy;
4854 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004855
4856 CGBuilderTy &Builder = CGF.Builder;
4857 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4858 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004859 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004860 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4861 llvm::Value *AddrTyped;
John McCall64aa4b32013-04-16 22:48:15 +00004862 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004863 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004864
4865 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004866 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4867 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4868 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4869 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004870 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4871 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4872 }
4873 else
4874 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4875
4876 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004877 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004878 uint64_t Offset =
4879 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4880 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004881 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004882 "ap.next");
4883 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4884
4885 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004886}
4887
John McCallaeeb7012010-05-27 06:19:26 +00004888bool
4889MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4890 llvm::Value *Address) const {
4891 // This information comes from gcc's implementation, which seems to
4892 // as canonical as it gets.
4893
John McCallaeeb7012010-05-27 06:19:26 +00004894 // Everything on MIPS is 4 bytes. Double-precision FP registers
4895 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004896 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00004897
4898 // 0-31 are the general purpose registers, $0 - $31.
4899 // 32-63 are the floating-point registers, $f0 - $f31.
4900 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4901 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00004902 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00004903
4904 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4905 // They are one bit wide and ignored here.
4906
4907 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4908 // (coprocessor 1 is the FP unit)
4909 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4910 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4911 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004912 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00004913 return false;
4914}
4915
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004916//===----------------------------------------------------------------------===//
4917// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4918// Currently subclassed only to implement custom OpenCL C function attribute
4919// handling.
4920//===----------------------------------------------------------------------===//
4921
4922namespace {
4923
4924class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4925public:
4926 TCETargetCodeGenInfo(CodeGenTypes &CGT)
4927 : DefaultTargetCodeGenInfo(CGT) {}
4928
4929 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4930 CodeGen::CodeGenModule &M) const;
4931};
4932
4933void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4934 llvm::GlobalValue *GV,
4935 CodeGen::CodeGenModule &M) const {
4936 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4937 if (!FD) return;
4938
4939 llvm::Function *F = cast<llvm::Function>(GV);
4940
David Blaikie4e4d0842012-03-11 07:00:24 +00004941 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004942 if (FD->hasAttr<OpenCLKernelAttr>()) {
4943 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004944 F->addFnAttr(llvm::Attribute::NoInline);
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004945
4946 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
4947
4948 // Convert the reqd_work_group_size() attributes to metadata.
4949 llvm::LLVMContext &Context = F->getContext();
4950 llvm::NamedMDNode *OpenCLMetadata =
4951 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
4952
4953 SmallVector<llvm::Value*, 5> Operands;
4954 Operands.push_back(F);
4955
Chris Lattner8b418682012-02-07 00:39:47 +00004956 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
4957 llvm::APInt(32,
4958 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
4959 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
4960 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004961 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00004962 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
4963 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004964 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
4965
4966 // Add a boolean constant operand for "required" (true) or "hint" (false)
4967 // for implementing the work_group_size_hint attr later. Currently
4968 // always true as the hint is not yet implemented.
Chris Lattner8b418682012-02-07 00:39:47 +00004969 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004970 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
4971 }
4972 }
4973 }
4974}
4975
4976}
John McCallaeeb7012010-05-27 06:19:26 +00004977
Tony Linthicum96319392011-12-12 21:14:55 +00004978//===----------------------------------------------------------------------===//
4979// Hexagon ABI Implementation
4980//===----------------------------------------------------------------------===//
4981
4982namespace {
4983
4984class HexagonABIInfo : public ABIInfo {
4985
4986
4987public:
4988 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4989
4990private:
4991
4992 ABIArgInfo classifyReturnType(QualType RetTy) const;
4993 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4994
4995 virtual void computeInfo(CGFunctionInfo &FI) const;
4996
4997 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4998 CodeGenFunction &CGF) const;
4999};
5000
5001class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5002public:
5003 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5004 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5005
5006 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5007 return 29;
5008 }
5009};
5010
5011}
5012
5013void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5014 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5015 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5016 it != ie; ++it)
5017 it->info = classifyArgumentType(it->type);
5018}
5019
5020ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5021 if (!isAggregateTypeForABI(Ty)) {
5022 // Treat an enum type as its underlying type.
5023 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5024 Ty = EnumTy->getDecl()->getIntegerType();
5025
5026 return (Ty->isPromotableIntegerType() ?
5027 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5028 }
5029
5030 // Ignore empty records.
5031 if (isEmptyRecord(getContext(), Ty, true))
5032 return ABIArgInfo::getIgnore();
5033
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005034 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
5035 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00005036
5037 uint64_t Size = getContext().getTypeSize(Ty);
5038 if (Size > 64)
5039 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5040 // Pass in the smallest viable integer type.
5041 else if (Size > 32)
5042 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5043 else if (Size > 16)
5044 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5045 else if (Size > 8)
5046 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5047 else
5048 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5049}
5050
5051ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5052 if (RetTy->isVoidType())
5053 return ABIArgInfo::getIgnore();
5054
5055 // Large vector types should be returned via memory.
5056 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5057 return ABIArgInfo::getIndirect(0);
5058
5059 if (!isAggregateTypeForABI(RetTy)) {
5060 // Treat an enum type as its underlying type.
5061 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5062 RetTy = EnumTy->getDecl()->getIntegerType();
5063
5064 return (RetTy->isPromotableIntegerType() ?
5065 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5066 }
5067
5068 // Structures with either a non-trivial destructor or a non-trivial
5069 // copy constructor are always indirect.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005070 if (isRecordReturnIndirect(RetTy, CGT))
Tony Linthicum96319392011-12-12 21:14:55 +00005071 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5072
5073 if (isEmptyRecord(getContext(), RetTy, true))
5074 return ABIArgInfo::getIgnore();
5075
5076 // Aggregates <= 8 bytes are returned in r0; other aggregates
5077 // are returned indirectly.
5078 uint64_t Size = getContext().getTypeSize(RetTy);
5079 if (Size <= 64) {
5080 // Return in the smallest viable integer type.
5081 if (Size <= 8)
5082 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5083 if (Size <= 16)
5084 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5085 if (Size <= 32)
5086 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5087 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5088 }
5089
5090 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5091}
5092
5093llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00005094 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00005095 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00005096 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00005097
5098 CGBuilderTy &Builder = CGF.Builder;
5099 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5100 "ap");
5101 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5102 llvm::Type *PTy =
5103 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5104 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5105
5106 uint64_t Offset =
5107 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5108 llvm::Value *NextAddr =
5109 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5110 "ap.next");
5111 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5112
5113 return AddrTyped;
5114}
5115
5116
Chris Lattnerea044322010-07-29 02:01:43 +00005117const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005118 if (TheTargetCodeGenInfo)
5119 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005120
John McCall64aa4b32013-04-16 22:48:15 +00005121 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00005122 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005123 default:
Chris Lattnerea044322010-07-29 02:01:43 +00005124 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005125
Derek Schuff9ed63f82012-09-06 17:37:28 +00005126 case llvm::Triple::le32:
5127 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00005128 case llvm::Triple::mips:
5129 case llvm::Triple::mipsel:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005130 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
John McCallaeeb7012010-05-27 06:19:26 +00005131
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005132 case llvm::Triple::mips64:
5133 case llvm::Triple::mips64el:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005134 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005135
Tim Northoverc264e162013-01-31 12:13:10 +00005136 case llvm::Triple::aarch64:
5137 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5138
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005139 case llvm::Triple::arm:
5140 case llvm::Triple::thumb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00005141 {
5142 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCall64aa4b32013-04-16 22:48:15 +00005143 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel34c1af82011-04-05 00:23:47 +00005144 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00005145 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00005146 (CodeGenOpts.FloatABI != "soft" &&
5147 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00005148 Kind = ARMABIInfo::AAPCS_VFP;
5149
Derek Schuff263366f2012-10-16 22:30:41 +00005150 switch (Triple.getOS()) {
Eli Bendersky441d9f72012-12-04 18:38:10 +00005151 case llvm::Triple::NaCl:
Derek Schuff263366f2012-10-16 22:30:41 +00005152 return *(TheTargetCodeGenInfo =
5153 new NaClARMTargetCodeGenInfo(Types, Kind));
5154 default:
5155 return *(TheTargetCodeGenInfo =
5156 new ARMTargetCodeGenInfo(Types, Kind));
5157 }
Sandeep Patel34c1af82011-04-05 00:23:47 +00005158 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005159
John McCallec853ba2010-03-11 00:10:12 +00005160 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00005161 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00005162 case llvm::Triple::ppc64:
Bill Schmidt2fc107f2012-10-03 19:18:57 +00005163 if (Triple.isOSBinFormatELF())
5164 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5165 else
5166 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
John McCallec853ba2010-03-11 00:10:12 +00005167
Peter Collingbourneedb66f32012-05-20 23:28:41 +00005168 case llvm::Triple::nvptx:
5169 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00005170 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005171
Wesley Peck276fdf42010-12-19 19:57:51 +00005172 case llvm::Triple::mblaze:
5173 return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types));
5174
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005175 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00005176 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005177
Ulrich Weigandb8409212013-05-06 16:26:41 +00005178 case llvm::Triple::systemz:
5179 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5180
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005181 case llvm::Triple::tce:
5182 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5183
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005184 case llvm::Triple::x86: {
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00005185 if (Triple.isOSDarwin())
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005186 return *(TheTargetCodeGenInfo =
Chad Rosier1f1df1f2013-03-25 21:00:27 +00005187 new X86_32TargetCodeGenInfo(Types, true, true, false,
Rafael Espindolab48280b2012-07-31 02:44:24 +00005188 CodeGenOpts.NumRegisterParameters));
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00005189
5190 switch (Triple.getOS()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005191 case llvm::Triple::Cygwin:
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005192 case llvm::Triple::MinGW32:
Edward O'Callaghan727e2682009-10-21 11:58:24 +00005193 case llvm::Triple::AuroraUX:
5194 case llvm::Triple::DragonFly:
David Chisnall75c135a2009-09-03 01:48:05 +00005195 case llvm::Triple::FreeBSD:
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005196 case llvm::Triple::OpenBSD:
Eli Friedman42f74f22012-08-08 23:57:20 +00005197 case llvm::Triple::Bitrig:
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005198 return *(TheTargetCodeGenInfo =
Chad Rosier1f1df1f2013-03-25 21:00:27 +00005199 new X86_32TargetCodeGenInfo(Types, false, true, false,
Rafael Espindolab48280b2012-07-31 02:44:24 +00005200 CodeGenOpts.NumRegisterParameters));
Eli Friedman55fc7e22012-01-25 22:46:34 +00005201
5202 case llvm::Triple::Win32:
5203 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00005204 new WinX86_32TargetCodeGenInfo(Types,
5205 CodeGenOpts.NumRegisterParameters));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005206
5207 default:
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005208 return *(TheTargetCodeGenInfo =
Chad Rosier1f1df1f2013-03-25 21:00:27 +00005209 new X86_32TargetCodeGenInfo(Types, false, false, false,
Rafael Espindolab48280b2012-07-31 02:44:24 +00005210 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005211 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005212 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005213
Eli Friedmanee1ad992011-12-02 00:11:43 +00005214 case llvm::Triple::x86_64: {
John McCall64aa4b32013-04-16 22:48:15 +00005215 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanee1ad992011-12-02 00:11:43 +00005216
Chris Lattnerf13721d2010-08-31 16:44:54 +00005217 switch (Triple.getOS()) {
5218 case llvm::Triple::Win32:
NAKAMURA Takumi0aa20572011-02-17 08:51:38 +00005219 case llvm::Triple::MinGW32:
Chris Lattnerf13721d2010-08-31 16:44:54 +00005220 case llvm::Triple::Cygwin:
5221 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Bendersky441d9f72012-12-04 18:38:10 +00005222 case llvm::Triple::NaCl:
John McCall64aa4b32013-04-16 22:48:15 +00005223 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5224 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005225 default:
Eli Friedmanee1ad992011-12-02 00:11:43 +00005226 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5227 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005228 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005229 }
Tony Linthicum96319392011-12-12 21:14:55 +00005230 case llvm::Triple::hexagon:
5231 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Eli Friedmanee1ad992011-12-02 00:11:43 +00005232 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005233}