blob: ba8b483052bbf8aaf72e1e37f4b5707984be6a6a [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-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 Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000021#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000022#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000025#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall943fae92010-05-27 06:19:26 +000029static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
30 llvm::Value *Array,
31 llvm::Value *Value,
32 unsigned FirstIndex,
33 unsigned LastIndex) {
34 // Alternatively, we could emit this as a loop in the source.
35 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
36 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
37 Builder.CreateStore(Value, Cell);
38 }
39}
40
John McCalla1dee5302010-08-22 10:59:02 +000041static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000042 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000043 T->isMemberFunctionPointerType();
44}
45
Anton Korobeynikov244360d2009-06-05 22:08:42 +000046ABIInfo::~ABIInfo() {}
47
Mark Lacey3825e832013-10-06 01:33:34 +000048static bool isRecordReturnIndirect(const RecordType *RT,
49 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000050 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
51 if (!RD)
52 return false;
Mark Lacey3825e832013-10-06 01:33:34 +000053 return CXXABI.isReturnTypeIndirect(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054}
55
56
Mark Lacey3825e832013-10-06 01:33:34 +000057static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058 const RecordType *RT = T->getAs<RecordType>();
59 if (!RT)
60 return false;
Mark Lacey3825e832013-10-06 01:33:34 +000061 return isRecordReturnIndirect(RT, CXXABI);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062}
63
64static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000065 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000066 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
67 if (!RD)
68 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000069 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070}
71
72static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000073 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000074 const RecordType *RT = T->getAs<RecordType>();
75 if (!RT)
76 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000077 return getRecordArgABI(RT, CXXABI);
78}
79
80CGCXXABI &ABIInfo::getCXXABI() const {
81 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000082}
83
Chris Lattner2b037972010-07-29 02:01:43 +000084ASTContext &ABIInfo::getContext() const {
85 return CGT.getContext();
86}
87
88llvm::LLVMContext &ABIInfo::getVMContext() const {
89 return CGT.getLLVMContext();
90}
91
Micah Villmowdd31ca12012-10-08 16:25:52 +000092const llvm::DataLayout &ABIInfo::getDataLayout() const {
93 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000094}
95
John McCallc8e01702013-04-16 22:48:15 +000096const TargetInfo &ABIInfo::getTarget() const {
97 return CGT.getTarget();
98}
Chris Lattner2b037972010-07-29 02:01:43 +000099
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000100void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000101 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000102 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000103 switch (TheKind) {
104 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000105 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000106 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000107 Ty->print(OS);
108 else
109 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000110 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000111 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000113 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000115 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000116 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000117 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000118 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000119 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000120 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
122 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127}
128
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000129TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
130
John McCall3480ef22011-08-30 01:42:09 +0000131// If someone can figure out a general rule for this, that would be great.
132// It's probably just doomed to be platform-dependent, though.
133unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
134 // Verified for:
135 // x86-64 FreeBSD, Linux, Darwin
136 // x86-32 FreeBSD, Linux, Darwin
137 // PowerPC Linux, Darwin
138 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000139 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000140 return 32;
141}
142
John McCalla729c622012-02-17 03:33:10 +0000143bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
144 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000145 // The following conventions are known to require this to be false:
146 // x86_stdcall
147 // MIPS
148 // For everything else, we just prefer false unless we opt out.
149 return false;
150}
151
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000152void
153TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
154 llvm::SmallString<24> &Opt) const {
155 // This assumes the user is passing a library name like "rt" instead of a
156 // filename like "librt.a/so", and that they don't care whether it's static or
157 // dynamic.
158 Opt = "-l";
159 Opt += Lib;
160}
161
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000162static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000164/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000165/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000166static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
167 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168 if (FD->isUnnamedBitfield())
169 return true;
170
171 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000172
Eli Friedman0b3f2012011-11-18 03:47:20 +0000173 // Constant arrays of empty records count as empty, strip them off.
174 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000175 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000176 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
177 if (AT->getSize() == 0)
178 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000179 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000180 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000181
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000182 const RecordType *RT = FT->getAs<RecordType>();
183 if (!RT)
184 return false;
185
186 // C++ record fields are never empty, at least in the Itanium ABI.
187 //
188 // FIXME: We should use a predicate for whether this behavior is true in the
189 // current ABI.
190 if (isa<CXXRecordDecl>(RT->getDecl()))
191 return false;
192
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000194}
195
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000196/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197/// fields. Note that a structure with a flexible array member is not
198/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000200 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000201 if (!RT)
202 return 0;
203 const RecordDecl *RD = RT->getDecl();
204 if (RD->hasFlexibleArrayMember())
205 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000206
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000207 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000208 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000209 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
210 e = CXXRD->bases_end(); i != e; ++i)
211 if (!isEmptyRecord(Context, i->getType(), true))
212 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000213
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000214 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
215 i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +0000216 if (!isEmptyField(Context, *i, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000217 return false;
218 return true;
219}
220
221/// isSingleElementStruct - Determine if a structure is a "single
222/// element struct", i.e. it has exactly one non-empty field or
223/// exactly one field which is itself a single element
224/// struct. Structures with flexible array members are never
225/// considered single element structs.
226///
227/// \return The field declaration for the single non-empty field, if
228/// it exists.
229static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
230 const RecordType *RT = T->getAsStructureType();
231 if (!RT)
232 return 0;
233
234 const RecordDecl *RD = RT->getDecl();
235 if (RD->hasFlexibleArrayMember())
236 return 0;
237
238 const Type *Found = 0;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000239
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000240 // If this is a C++ record, check the bases first.
241 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
242 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
243 e = CXXRD->bases_end(); i != e; ++i) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000244 // Ignore empty records.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000245 if (isEmptyRecord(Context, i->getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000246 continue;
247
248 // If we already found an element then this isn't a single-element struct.
249 if (Found)
250 return 0;
251
252 // If this is non-empty and not a single element struct, the composite
253 // cannot be a single element struct.
254 Found = isSingleElementStruct(i->getType(), Context);
255 if (!Found)
256 return 0;
257 }
258 }
259
260 // Check for single element.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000261 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
262 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000263 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000264 QualType FT = FD->getType();
265
266 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000267 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000268 continue;
269
270 // If we already found an element then this isn't a single-element
271 // struct.
272 if (Found)
273 return 0;
274
275 // Treat single element arrays as the element.
276 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
277 if (AT->getSize().getZExtValue() != 1)
278 break;
279 FT = AT->getElementType();
280 }
281
John McCalla1dee5302010-08-22 10:59:02 +0000282 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283 Found = FT.getTypePtr();
284 } else {
285 Found = isSingleElementStruct(FT, Context);
286 if (!Found)
287 return 0;
288 }
289 }
290
Eli Friedmanee945342011-11-18 01:25:50 +0000291 // We don't consider a struct a single-element struct if it has
292 // padding beyond the element type.
293 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
294 return 0;
295
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 return Found;
297}
298
299static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000300 // Treat complex types as the element type.
301 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
302 Ty = CTy->getElementType();
303
304 // Check for a type which we know has a simple scalar argument-passing
305 // convention without any padding. (We're specifically looking for 32
306 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000307 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000308 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000309 return false;
310
311 uint64_t Size = Context.getTypeSize(Ty);
312 return Size == 32 || Size == 64;
313}
314
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000315/// canExpandIndirectArgument - Test whether an argument type which is to be
316/// passed indirectly (on the stack) would have the equivalent layout if it was
317/// expanded into separate arguments. If so, we prefer to do the latter to avoid
318/// inhibiting optimizations.
319///
320// FIXME: This predicate is missing many cases, currently it just follows
321// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
322// should probably make this smarter, or better yet make the LLVM backend
323// capable of handling it.
324static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
325 // We can only expand structure types.
326 const RecordType *RT = Ty->getAs<RecordType>();
327 if (!RT)
328 return false;
329
330 // We can only expand (C) structures.
331 //
332 // FIXME: This needs to be generalized to handle classes as well.
333 const RecordDecl *RD = RT->getDecl();
334 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
335 return false;
336
Eli Friedmane5c85622011-11-18 01:32:26 +0000337 uint64_t Size = 0;
338
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000339 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
340 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000341 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000342
343 if (!is32Or64BitBasicType(FD->getType(), Context))
344 return false;
345
346 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
347 // how to expand them yet, and the predicate for telling if a bitfield still
348 // counts as "basic" is more complicated than what we were doing previously.
349 if (FD->isBitField())
350 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000351
352 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000353 }
354
Eli Friedmane5c85622011-11-18 01:32:26 +0000355 // Make sure there are not any holes in the struct.
356 if (Size != Context.getTypeSize(Ty))
357 return false;
358
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359 return true;
360}
361
362namespace {
363/// DefaultABIInfo - The default implementation for ABI specific
364/// details. This implementation provides information which results in
365/// self-consistent and sensible LLVM IR generation, but does not
366/// conform to any particular ABI.
367class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000368public:
369 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000370
Chris Lattner458b2aa2010-07-29 02:16:43 +0000371 ABIArgInfo classifyReturnType(QualType RetTy) const;
372 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000373
Chris Lattner22326a12010-07-29 02:31:05 +0000374 virtual void computeInfo(CGFunctionInfo &FI) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000375 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000376 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
377 it != ie; ++it)
Chris Lattner458b2aa2010-07-29 02:16:43 +0000378 it->info = classifyArgumentType(it->type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000379 }
380
381 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
382 CodeGenFunction &CGF) const;
383};
384
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000385class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
386public:
Chris Lattner2b037972010-07-29 02:01:43 +0000387 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
388 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000389};
390
391llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
392 CodeGenFunction &CGF) const {
393 return 0;
394}
395
Chris Lattner458b2aa2010-07-29 02:16:43 +0000396ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung180319f2011-11-03 00:59:44 +0000397 if (isAggregateTypeForABI(Ty)) {
Alp Tokerd4733632013-12-05 04:47:09 +0000398 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung180319f2011-11-03 00:59:44 +0000399 // by value.
Mark Lacey3825e832013-10-06 01:33:34 +0000400 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung180319f2011-11-03 00:59:44 +0000401 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
402
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000403 return ABIArgInfo::getIndirect(0);
Jan Wen Voung180319f2011-11-03 00:59:44 +0000404 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000405
Chris Lattner9723d6c2010-03-11 18:19:55 +0000406 // Treat an enum type as its underlying type.
407 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
408 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000409
Chris Lattner9723d6c2010-03-11 18:19:55 +0000410 return (Ty->isPromotableIntegerType() ?
411 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000412}
413
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000414ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
415 if (RetTy->isVoidType())
416 return ABIArgInfo::getIgnore();
417
418 if (isAggregateTypeForABI(RetTy))
419 return ABIArgInfo::getIndirect(0);
420
421 // Treat an enum type as its underlying type.
422 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
423 RetTy = EnumTy->getDecl()->getIntegerType();
424
425 return (RetTy->isPromotableIntegerType() ?
426 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
427}
428
Derek Schuff09338a22012-09-06 17:37:28 +0000429//===----------------------------------------------------------------------===//
430// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000431//
432// This is a simplified version of the x86_32 ABI. Arguments and return values
433// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000434//===----------------------------------------------------------------------===//
435
436class PNaClABIInfo : public ABIInfo {
437 public:
438 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
439
440 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000441 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000442
443 virtual void computeInfo(CGFunctionInfo &FI) const;
444 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
445 CodeGenFunction &CGF) const;
446};
447
448class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
449 public:
450 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
451 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
452};
453
454void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456
Derek Schuff09338a22012-09-06 17:37:28 +0000457 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
458 it != ie; ++it)
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 it->info = classifyArgumentType(it->type);
Derek Schuff09338a22012-09-06 17:37:28 +0000460 }
461
462llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463 CodeGenFunction &CGF) const {
464 return 0;
465}
466
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000467/// \brief Classify argument of given type \p Ty.
468ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000469 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000470 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000471 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000472 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000473 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
474 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000475 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000476 } else if (Ty->isFloatingType()) {
477 // Floating-point types don't go inreg.
478 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000479 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000480
481 return (Ty->isPromotableIntegerType() ?
482 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000483}
484
485ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
486 if (RetTy->isVoidType())
487 return ABIArgInfo::getIgnore();
488
Eli Benderskye20dad62013-04-04 22:49:35 +0000489 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000490 if (isAggregateTypeForABI(RetTy))
491 return ABIArgInfo::getIndirect(0);
492
493 // Treat an enum type as its underlying type.
494 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
495 RetTy = EnumTy->getDecl()->getIntegerType();
496
497 return (RetTy->isPromotableIntegerType() ?
498 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
499}
500
Chad Rosier651c1832013-03-25 21:00:27 +0000501/// IsX86_MMXType - Return true if this is an MMX type.
502bool IsX86_MMXType(llvm::Type *IRType) {
503 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000504 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
505 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
506 IRType->getScalarSizeInBits() != 64;
507}
508
Jay Foad7c57be32011-07-11 09:56:20 +0000509static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000511 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000512 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
513 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
514 // Invalid MMX constraint
515 return 0;
516 }
517
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000518 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000519 }
520
521 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000522 return Ty;
523}
524
Chris Lattner0cf24192010-06-28 20:05:43 +0000525//===----------------------------------------------------------------------===//
526// X86-32 ABI Implementation
527//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000528
Reid Kleckner661f35b2014-01-18 01:12:41 +0000529/// \brief Similar to llvm::CCState, but for Clang.
530struct CCState {
531 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
532
533 unsigned CC;
534 unsigned FreeRegs;
535};
536
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000537/// X86_32ABIInfo - The X86-32 ABI information.
538class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000539 enum Class {
540 Integer,
541 Float
542 };
543
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000544 static const unsigned MinABIStackAlignInBytes = 4;
545
David Chisnallde3a0692009-08-17 23:08:21 +0000546 bool IsDarwinVectorABI;
547 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000548 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000549 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000550
551 static bool isRegisterSize(unsigned Size) {
552 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
553 }
554
Aaron Ballman3c424412012-02-22 03:04:13 +0000555 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
556 unsigned callingConvention);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000557
Daniel Dunbar557893d2010-04-21 19:10:51 +0000558 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
559 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000560 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
561
562 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000563
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000564 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000565 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000566
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000567 Class classify(QualType Ty) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000568 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
569 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
570 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000571
Rafael Espindola75419dc2012-07-23 23:30:29 +0000572public:
573
Rafael Espindolaa6472962012-07-24 00:01:07 +0000574 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000575 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
576 CodeGenFunction &CGF) const;
577
Chad Rosier651c1832013-03-25 21:00:27 +0000578 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000579 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000580 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000581 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000582};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000583
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000584class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
585public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000586 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000587 bool d, bool p, bool w, unsigned r)
588 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000589
John McCall1fe2a8c2013-06-18 02:46:29 +0000590 static bool isStructReturnInRegABI(
591 const llvm::Triple &Triple, const CodeGenOptions &Opts);
592
Charles Davis4ea31ab2010-02-13 15:54:06 +0000593 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
594 CodeGen::CodeGenModule &CGM) const;
John McCallbeec5a02010-03-06 00:35:14 +0000595
596 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
597 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000598 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000599 return 4;
600 }
601
602 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
603 llvm::Value *Address) const;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000604
Jay Foad7c57be32011-07-11 09:56:20 +0000605 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000607 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000608 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
609 }
610
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000611 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
612 unsigned Sig = (0xeb << 0) | // jmp rel8
613 (0x06 << 8) | // .+0x08
614 ('F' << 16) |
615 ('T' << 24);
616 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
617 }
618
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000619};
620
621}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622
623/// shouldReturnTypeInRegister - Determine if the given type should be
624/// passed in a register (for the Darwin ABI).
625bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
Aaron Ballman3c424412012-02-22 03:04:13 +0000626 ASTContext &Context,
627 unsigned callingConvention) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000628 uint64_t Size = Context.getTypeSize(Ty);
629
630 // Type must be register sized.
631 if (!isRegisterSize(Size))
632 return false;
633
634 if (Ty->isVectorType()) {
635 // 64- and 128- bit vectors inside structures are not returned in
636 // registers.
637 if (Size == 64 || Size == 128)
638 return false;
639
640 return true;
641 }
642
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000643 // If this is a builtin, pointer, enum, complex type, member pointer, or
644 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000645 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000646 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000647 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000648 return true;
649
650 // Arrays are treated like records.
651 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman3c424412012-02-22 03:04:13 +0000652 return shouldReturnTypeInRegister(AT->getElementType(), Context,
653 callingConvention);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000654
655 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000656 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000657 if (!RT) return false;
658
Anders Carlsson40446e82010-01-27 03:25:19 +0000659 // FIXME: Traverse bases here too.
660
Aaron Ballman3c424412012-02-22 03:04:13 +0000661 // For thiscall conventions, structures will never be returned in
662 // a register. This is for compatibility with the MSVC ABI
663 if (callingConvention == llvm::CallingConv::X86_ThisCall &&
664 RT->isStructureType()) {
665 return false;
666 }
667
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000668 // Structure types are passed in register if all fields would be
669 // passed in a register.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000670 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
671 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000672 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000673
674 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000675 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000676 continue;
677
678 // Check fields recursively.
Aaron Ballman3c424412012-02-22 03:04:13 +0000679 if (!shouldReturnTypeInRegister(FD->getType(), Context,
680 callingConvention))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000681 return false;
682 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000683 return true;
684}
685
Reid Kleckner661f35b2014-01-18 01:12:41 +0000686ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
687 // If the return value is indirect, then the hidden argument is consuming one
688 // integer register.
689 if (State.FreeRegs) {
690 --State.FreeRegs;
691 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
692 }
693 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
694}
695
696ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
697 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000698 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000699 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000700
Chris Lattner458b2aa2010-07-29 02:16:43 +0000701 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000702 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000703 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000704 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000705
706 // 128-bit vectors are a special case; they are returned in
707 // registers and we need to make sure to pick a type the LLVM
708 // backend will like.
709 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000710 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000711 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000712
713 // Always return in register if it fits in a general purpose
714 // register, or if it is 64 bits and has a single element.
715 if ((Size == 8 || Size == 16 || Size == 32) ||
716 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000717 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000718 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000719
Reid Kleckner661f35b2014-01-18 01:12:41 +0000720 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000721 }
722
723 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000724 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000725
John McCalla1dee5302010-08-22 10:59:02 +0000726 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000727 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000728 if (isRecordReturnIndirect(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000729 return getIndirectReturnResult(State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000730
Anders Carlsson5789c492009-10-20 22:07:59 +0000731 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000732 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000733 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000734 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000735
David Chisnallde3a0692009-08-17 23:08:21 +0000736 // If specified, structs and unions are always indirect.
737 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000738 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000739
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000740 // Small structures which are register sized are generally returned
741 // in a register.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000742 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
743 State.CC)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000744 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000745
746 // As a special-case, if the struct is a "single-element" struct, and
747 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000748 // floating-point register. (MSVC does not apply this special case.)
749 // We apply a similar transformation for pointer types to improve the
750 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000751 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000752 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000753 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000754 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
755
756 // FIXME: We should be able to narrow this integer in cases with dead
757 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000758 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000759 }
760
Reid Kleckner661f35b2014-01-18 01:12:41 +0000761 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000762 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000763
Chris Lattner458b2aa2010-07-29 02:16:43 +0000764 // Treat an enum type as its underlying type.
765 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
766 RetTy = EnumTy->getDecl()->getIntegerType();
767
768 return (RetTy->isPromotableIntegerType() ?
769 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000770}
771
Eli Friedman7919bea2012-06-05 19:40:46 +0000772static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
773 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
774}
775
Daniel Dunbared23de32010-09-16 20:42:00 +0000776static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
777 const RecordType *RT = Ty->getAs<RecordType>();
778 if (!RT)
779 return 0;
780 const RecordDecl *RD = RT->getDecl();
781
782 // If this is a C++ record, check the bases first.
783 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
784 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
785 e = CXXRD->bases_end(); i != e; ++i)
786 if (!isRecordWithSSEVectorType(Context, i->getType()))
787 return false;
788
789 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
790 i != e; ++i) {
791 QualType FT = i->getType();
792
Eli Friedman7919bea2012-06-05 19:40:46 +0000793 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000794 return true;
795
796 if (isRecordWithSSEVectorType(Context, FT))
797 return true;
798 }
799
800 return false;
801}
802
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000803unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
804 unsigned Align) const {
805 // Otherwise, if the alignment is less than or equal to the minimum ABI
806 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000807 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000808 return 0; // Use default alignment.
809
810 // On non-Darwin, the stack type alignment is always 4.
811 if (!IsDarwinVectorABI) {
812 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000813 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000814 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000815
Daniel Dunbared23de32010-09-16 20:42:00 +0000816 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000817 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
818 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000819 return 16;
820
821 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000822}
823
Rafael Espindola703c47f2012-10-19 05:04:37 +0000824ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000825 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000826 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000827 if (State.FreeRegs) {
828 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000829 return ABIArgInfo::getIndirectInReg(0, false);
830 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000831 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000832 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000833
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000834 // Compute the byval alignment.
835 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
836 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
837 if (StackAlign == 0)
Chris Lattnere76b95a2011-05-22 23:35:00 +0000838 return ABIArgInfo::getIndirect(4);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000839
840 // If the stack alignment is less than the type alignment, realign the
841 // argument.
842 if (StackAlign < TypeAlign)
843 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
844 /*Realign=*/true);
845
846 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000847}
848
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000849X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
850 const Type *T = isSingleElementStruct(Ty, getContext());
851 if (!T)
852 T = Ty.getTypePtr();
853
854 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
855 BuiltinType::Kind K = BT->getKind();
856 if (K == BuiltinType::Float || K == BuiltinType::Double)
857 return Float;
858 }
859 return Integer;
860}
861
Reid Kleckner661f35b2014-01-18 01:12:41 +0000862bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
863 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000864 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000865 Class C = classify(Ty);
866 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000867 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000868
Rafael Espindola077dd592012-10-24 01:58:58 +0000869 unsigned Size = getContext().getTypeSize(Ty);
870 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000871
872 if (SizeInRegs == 0)
873 return false;
874
Reid Kleckner661f35b2014-01-18 01:12:41 +0000875 if (SizeInRegs > State.FreeRegs) {
876 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000877 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000878 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000879
Reid Kleckner661f35b2014-01-18 01:12:41 +0000880 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000881
Reid Kleckner661f35b2014-01-18 01:12:41 +0000882 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000883 if (Size > 32)
884 return false;
885
886 if (Ty->isIntegralOrEnumerationType())
887 return true;
888
889 if (Ty->isPointerType())
890 return true;
891
892 if (Ty->isReferenceType())
893 return true;
894
Reid Kleckner661f35b2014-01-18 01:12:41 +0000895 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000896 NeedsPadding = true;
897
Rafael Espindola077dd592012-10-24 01:58:58 +0000898 return false;
899 }
900
Rafael Espindola703c47f2012-10-19 05:04:37 +0000901 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000902}
903
Reid Kleckner661f35b2014-01-18 01:12:41 +0000904ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000905 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000906 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000907 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000908 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000909 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000910
Mark Lacey3825e832013-10-06 01:33:34 +0000911 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000912 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory,
913 State);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000914
915 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000916 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000917 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000918 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000919
Eli Friedman9f061a32011-11-18 00:28:11 +0000920 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000921 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000922 return ABIArgInfo::getIgnore();
923
Rafael Espindolafad28de2012-10-24 01:59:00 +0000924 llvm::LLVMContext &LLVMContext = getVMContext();
925 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
926 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000927 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000928 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000929 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000930 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
931 return ABIArgInfo::getDirectInReg(Result);
932 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000933 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000934
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000935 // Expand small (<= 128-bit) record types when we know that the stack layout
936 // of those arguments will match the struct. This is important because the
937 // LLVM backend isn't smart enough to remove byval, which inhibits many
938 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000939 if (getContext().getTypeSize(Ty) <= 4*32 &&
940 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000941 return ABIArgInfo::getExpandWithPadding(
942 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000943
Reid Kleckner661f35b2014-01-18 01:12:41 +0000944 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000945 }
946
Chris Lattnerd774ae92010-08-26 20:05:13 +0000947 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000948 // On Darwin, some vectors are passed in memory, we handle this by passing
949 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000950 if (IsDarwinVectorABI) {
951 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000952 if ((Size == 8 || Size == 16 || Size == 32) ||
953 (Size == 64 && VT->getNumElements() == 1))
954 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
955 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000956 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000957
Chad Rosier651c1832013-03-25 21:00:27 +0000958 if (IsX86_MMXType(CGT.ConvertType(Ty)))
959 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000960
Chris Lattnerd774ae92010-08-26 20:05:13 +0000961 return ABIArgInfo::getDirect();
962 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000963
964
Chris Lattner458b2aa2010-07-29 02:16:43 +0000965 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
966 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000967
Rafael Espindolafad28de2012-10-24 01:59:00 +0000968 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000969 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000970
971 if (Ty->isPromotableIntegerType()) {
972 if (InReg)
973 return ABIArgInfo::getExtendInReg();
974 return ABIArgInfo::getExtend();
975 }
976 if (InReg)
977 return ABIArgInfo::getDirectInReg();
978 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000979}
980
Rafael Espindolaa6472962012-07-24 00:01:07 +0000981void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000982 CCState State(FI.getCallingConvention());
983 if (State.CC == llvm::CallingConv::X86_FastCall)
984 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000985 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000986 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +0000987 else
Reid Kleckner661f35b2014-01-18 01:12:41 +0000988 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000989
Reid Kleckner661f35b2014-01-18 01:12:41 +0000990 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000991
Rafael Espindolaa6472962012-07-24 00:01:07 +0000992 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
993 it != ie; ++it)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994 it->info = classifyArgumentType(it->type, State);
Rafael Espindolaa6472962012-07-24 00:01:07 +0000995}
996
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000997llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
998 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +0000999 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001000
1001 CGBuilderTy &Builder = CGF.Builder;
1002 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1003 "ap");
1004 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001005
1006 // Compute if the address needs to be aligned
1007 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1008 Align = getTypeStackAlignInBytes(Ty, Align);
1009 Align = std::max(Align, 4U);
1010 if (Align > 4) {
1011 // addr = (addr + align - 1) & -align;
1012 llvm::Value *Offset =
1013 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1014 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1015 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1016 CGF.Int32Ty);
1017 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1018 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1019 Addr->getType(),
1020 "ap.cur.aligned");
1021 }
1022
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001023 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001024 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001025 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1026
1027 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001028 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001029 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001030 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001031 "ap.next");
1032 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1033
1034 return AddrTyped;
1035}
1036
Charles Davis4ea31ab2010-02-13 15:54:06 +00001037void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1038 llvm::GlobalValue *GV,
1039 CodeGen::CodeGenModule &CGM) const {
1040 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1041 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1042 // Get the LLVM function.
1043 llvm::Function *Fn = cast<llvm::Function>(GV);
1044
1045 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001046 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001047 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001048 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1049 llvm::AttributeSet::get(CGM.getLLVMContext(),
1050 llvm::AttributeSet::FunctionIndex,
1051 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001052 }
1053 }
1054}
1055
John McCallbeec5a02010-03-06 00:35:14 +00001056bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1057 CodeGen::CodeGenFunction &CGF,
1058 llvm::Value *Address) const {
1059 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001060
Chris Lattnerece04092012-02-07 00:39:47 +00001061 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001062
John McCallbeec5a02010-03-06 00:35:14 +00001063 // 0-7 are the eight integer registers; the order is different
1064 // on Darwin (for EH), but the range is the same.
1065 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001066 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001067
John McCallc8e01702013-04-16 22:48:15 +00001068 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001069 // 12-16 are st(0..4). Not sure why we stop at 4.
1070 // These have size 16, which is sizeof(long double) on
1071 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001072 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001073 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001074
John McCallbeec5a02010-03-06 00:35:14 +00001075 } else {
1076 // 9 is %eflags, which doesn't get a size on Darwin for some
1077 // reason.
1078 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1079
1080 // 11-16 are st(0..5). Not sure why we stop at 5.
1081 // These have size 12, which is sizeof(long double) on
1082 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001083 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001084 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1085 }
John McCallbeec5a02010-03-06 00:35:14 +00001086
1087 return false;
1088}
1089
Chris Lattner0cf24192010-06-28 20:05:43 +00001090//===----------------------------------------------------------------------===//
1091// X86-64 ABI Implementation
1092//===----------------------------------------------------------------------===//
1093
1094
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001095namespace {
1096/// X86_64ABIInfo - The X86_64 ABI information.
1097class X86_64ABIInfo : public ABIInfo {
1098 enum Class {
1099 Integer = 0,
1100 SSE,
1101 SSEUp,
1102 X87,
1103 X87Up,
1104 ComplexX87,
1105 NoClass,
1106 Memory
1107 };
1108
1109 /// merge - Implement the X86_64 ABI merging algorithm.
1110 ///
1111 /// Merge an accumulating classification \arg Accum with a field
1112 /// classification \arg Field.
1113 ///
1114 /// \param Accum - The accumulating classification. This should
1115 /// always be either NoClass or the result of a previous merge
1116 /// call. In addition, this should never be Memory (the caller
1117 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001118 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001119
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001120 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1121 ///
1122 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1123 /// final MEMORY or SSE classes when necessary.
1124 ///
1125 /// \param AggregateSize - The size of the current aggregate in
1126 /// the classification process.
1127 ///
1128 /// \param Lo - The classification for the parts of the type
1129 /// residing in the low word of the containing object.
1130 ///
1131 /// \param Hi - The classification for the parts of the type
1132 /// residing in the higher words of the containing object.
1133 ///
1134 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1135
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001136 /// classify - Determine the x86_64 register classes in which the
1137 /// given type T should be passed.
1138 ///
1139 /// \param Lo - The classification for the parts of the type
1140 /// residing in the low word of the containing object.
1141 ///
1142 /// \param Hi - The classification for the parts of the type
1143 /// residing in the high word of the containing object.
1144 ///
1145 /// \param OffsetBase - The bit offset of this type in the
1146 /// containing object. Some parameters are classified different
1147 /// depending on whether they straddle an eightbyte boundary.
1148 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001149 /// \param isNamedArg - Whether the argument in question is a "named"
1150 /// argument, as used in AMD64-ABI 3.5.7.
1151 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001152 /// If a word is unused its result will be NoClass; if a type should
1153 /// be passed in Memory then at least the classification of \arg Lo
1154 /// will be Memory.
1155 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001156 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001157 ///
1158 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1159 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001160 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1161 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001162
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001163 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001164 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1165 unsigned IROffset, QualType SourceTy,
1166 unsigned SourceOffset) const;
1167 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1168 unsigned IROffset, QualType SourceTy,
1169 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001170
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001171 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001172 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001173 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001174
1175 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001176 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001177 ///
1178 /// \param freeIntRegs - The number of free integer registers remaining
1179 /// available.
1180 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181
Chris Lattner458b2aa2010-07-29 02:16:43 +00001182 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001183
Bill Wendling5cd41c42010-10-18 03:41:31 +00001184 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001185 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001186 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001187 unsigned &neededSSE,
1188 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001189
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001190 bool IsIllegalVectorType(QualType Ty) const;
1191
John McCalle0fda732011-04-21 01:20:55 +00001192 /// The 0.98 ABI revision clarified a lot of ambiguities,
1193 /// unfortunately in ways that were not always consistent with
1194 /// certain previous compilers. In particular, platforms which
1195 /// required strict binary compatibility with older versions of GCC
1196 /// may need to exempt themselves.
1197 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001198 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001199 }
1200
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001201 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001202 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1203 // 64-bit hardware.
1204 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001205
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001207 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001208 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001209 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001210 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001211
John McCalla729c622012-02-17 03:33:10 +00001212 bool isPassedUsingAVXType(QualType type) const {
1213 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001214 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001215 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1216 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001217 if (info.isDirect()) {
1218 llvm::Type *ty = info.getCoerceToType();
1219 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1220 return (vectorTy->getBitWidth() > 128);
1221 }
1222 return false;
1223 }
1224
Chris Lattner22326a12010-07-29 02:31:05 +00001225 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001226
1227 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1228 CodeGenFunction &CGF) const;
1229};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001230
Chris Lattner04dc9572010-08-31 16:44:54 +00001231/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001232class WinX86_64ABIInfo : public ABIInfo {
1233
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001234 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001235
Chris Lattner04dc9572010-08-31 16:44:54 +00001236public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001237 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1238
1239 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattner04dc9572010-08-31 16:44:54 +00001240
1241 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1242 CodeGenFunction &CGF) const;
1243};
1244
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001245class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1246public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001247 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001248 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001249
John McCalla729c622012-02-17 03:33:10 +00001250 const X86_64ABIInfo &getABIInfo() const {
1251 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1252 }
1253
John McCallbeec5a02010-03-06 00:35:14 +00001254 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1255 return 7;
1256 }
1257
1258 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1259 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001260 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001261
John McCall943fae92010-05-27 06:19:26 +00001262 // 0-15 are the 16 integer registers.
1263 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001264 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001265 return false;
1266 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001267
Jay Foad7c57be32011-07-11 09:56:20 +00001268 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001269 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +00001270 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001271 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1272 }
1273
John McCalla729c622012-02-17 03:33:10 +00001274 bool isNoProtoCallVariadic(const CallArgList &args,
1275 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +00001276 // The default CC on x86-64 sets %al to the number of SSA
1277 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001278 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001279 // that when AVX types are involved: the ABI explicitly states it is
1280 // undefined, and it doesn't work in practice because of how the ABI
1281 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001282 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001283 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001284 for (CallArgList::const_iterator
1285 it = args.begin(), ie = args.end(); it != ie; ++it) {
1286 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1287 HasAVXType = true;
1288 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001289 }
1290 }
John McCalla729c622012-02-17 03:33:10 +00001291
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001292 if (!HasAVXType)
1293 return true;
1294 }
John McCallcbc038a2011-09-21 08:08:30 +00001295
John McCalla729c622012-02-17 03:33:10 +00001296 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001297 }
1298
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001299 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
1300 unsigned Sig = (0xeb << 0) | // jmp rel8
1301 (0x0a << 8) | // .+0x0c
1302 ('F' << 16) |
1303 ('T' << 24);
1304 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1305 }
1306
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001307};
1308
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001309static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1310 // If the argument does not end in .lib, automatically add the suffix. This
1311 // matches the behavior of MSVC.
1312 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001313 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001314 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001315 return ArgStr;
1316}
1317
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001318class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1319public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001320 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1321 bool d, bool p, bool w, unsigned RegParms)
1322 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001323
1324 void getDependentLibraryOption(llvm::StringRef Lib,
1325 llvm::SmallString<24> &Opt) const {
1326 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001327 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001328 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001329
1330 void getDetectMismatchOption(llvm::StringRef Name,
1331 llvm::StringRef Value,
1332 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001333 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001334 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001335};
1336
Chris Lattner04dc9572010-08-31 16:44:54 +00001337class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1338public:
1339 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1340 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1341
1342 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1343 return 7;
1344 }
1345
1346 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1347 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001348 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001349
Chris Lattner04dc9572010-08-31 16:44:54 +00001350 // 0-15 are the 16 integer registers.
1351 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001352 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001353 return false;
1354 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001355
1356 void getDependentLibraryOption(llvm::StringRef Lib,
1357 llvm::SmallString<24> &Opt) const {
1358 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001359 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001360 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001361
1362 void getDetectMismatchOption(llvm::StringRef Name,
1363 llvm::StringRef Value,
1364 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001365 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001366 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001367};
1368
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001369}
1370
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001371void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1372 Class &Hi) const {
1373 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1374 //
1375 // (a) If one of the classes is Memory, the whole argument is passed in
1376 // memory.
1377 //
1378 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1379 // memory.
1380 //
1381 // (c) If the size of the aggregate exceeds two eightbytes and the first
1382 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1383 // argument is passed in memory. NOTE: This is necessary to keep the
1384 // ABI working for processors that don't support the __m256 type.
1385 //
1386 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1387 //
1388 // Some of these are enforced by the merging logic. Others can arise
1389 // only with unions; for example:
1390 // union { _Complex double; unsigned; }
1391 //
1392 // Note that clauses (b) and (c) were added in 0.98.
1393 //
1394 if (Hi == Memory)
1395 Lo = Memory;
1396 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1397 Lo = Memory;
1398 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1399 Lo = Memory;
1400 if (Hi == SSEUp && Lo != SSE)
1401 Hi = SSE;
1402}
1403
Chris Lattnerd776fb12010-06-28 21:43:59 +00001404X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001405 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1406 // classified recursively so that always two fields are
1407 // considered. The resulting class is calculated according to
1408 // the classes of the fields in the eightbyte:
1409 //
1410 // (a) If both classes are equal, this is the resulting class.
1411 //
1412 // (b) If one of the classes is NO_CLASS, the resulting class is
1413 // the other class.
1414 //
1415 // (c) If one of the classes is MEMORY, the result is the MEMORY
1416 // class.
1417 //
1418 // (d) If one of the classes is INTEGER, the result is the
1419 // INTEGER.
1420 //
1421 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1422 // MEMORY is used as class.
1423 //
1424 // (f) Otherwise class SSE is used.
1425
1426 // Accum should never be memory (we should have returned) or
1427 // ComplexX87 (because this cannot be passed in a structure).
1428 assert((Accum != Memory && Accum != ComplexX87) &&
1429 "Invalid accumulated classification during merge.");
1430 if (Accum == Field || Field == NoClass)
1431 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001432 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001433 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001434 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001435 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001436 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001437 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001438 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1439 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001440 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001441 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001442}
1443
Chris Lattner5c740f12010-06-30 19:14:05 +00001444void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001445 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001446 // FIXME: This code can be simplified by introducing a simple value class for
1447 // Class pairs with appropriate constructor methods for the various
1448 // situations.
1449
1450 // FIXME: Some of the split computations are wrong; unaligned vectors
1451 // shouldn't be passed in registers for example, so there is no chance they
1452 // can straddle an eightbyte. Verify & simplify.
1453
1454 Lo = Hi = NoClass;
1455
1456 Class &Current = OffsetBase < 64 ? Lo : Hi;
1457 Current = Memory;
1458
John McCall9dd450b2009-09-21 23:43:11 +00001459 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001460 BuiltinType::Kind k = BT->getKind();
1461
1462 if (k == BuiltinType::Void) {
1463 Current = NoClass;
1464 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1465 Lo = Integer;
1466 Hi = Integer;
1467 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1468 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001469 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1470 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001471 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001472 Current = SSE;
1473 } else if (k == BuiltinType::LongDouble) {
1474 Lo = X87;
1475 Hi = X87Up;
1476 }
1477 // FIXME: _Decimal32 and _Decimal64 are SSE.
1478 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001479 return;
1480 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001481
Chris Lattnerd776fb12010-06-28 21:43:59 +00001482 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001483 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001484 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001485 return;
1486 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001487
Chris Lattnerd776fb12010-06-28 21:43:59 +00001488 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001489 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001490 return;
1491 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001492
Chris Lattnerd776fb12010-06-28 21:43:59 +00001493 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001494 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001495 Lo = Hi = Integer;
1496 else
1497 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001498 return;
1499 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001500
Chris Lattnerd776fb12010-06-28 21:43:59 +00001501 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001502 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001503 if (Size == 32) {
1504 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1505 // float> as integer.
1506 Current = Integer;
1507
1508 // If this type crosses an eightbyte boundary, it should be
1509 // split.
1510 uint64_t EB_Real = (OffsetBase) / 64;
1511 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1512 if (EB_Real != EB_Imag)
1513 Hi = Lo;
1514 } else if (Size == 64) {
1515 // gcc passes <1 x double> in memory. :(
1516 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1517 return;
1518
1519 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001520 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001521 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1522 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1523 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001524 Current = Integer;
1525 else
1526 Current = SSE;
1527
1528 // If this type crosses an eightbyte boundary, it should be
1529 // split.
1530 if (OffsetBase && OffsetBase != 64)
1531 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001532 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001533 // Arguments of 256-bits are split into four eightbyte chunks. The
1534 // least significant one belongs to class SSE and all the others to class
1535 // SSEUP. The original Lo and Hi design considers that types can't be
1536 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1537 // This design isn't correct for 256-bits, but since there're no cases
1538 // where the upper parts would need to be inspected, avoid adding
1539 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001540 //
1541 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1542 // registers if they are "named", i.e. not part of the "..." of a
1543 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001544 Lo = SSE;
1545 Hi = SSEUp;
1546 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001547 return;
1548 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001549
Chris Lattnerd776fb12010-06-28 21:43:59 +00001550 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001551 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001552
Chris Lattner2b037972010-07-29 02:01:43 +00001553 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001554 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001555 if (Size <= 64)
1556 Current = Integer;
1557 else if (Size <= 128)
1558 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001559 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001560 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001561 else if (ET == getContext().DoubleTy ||
1562 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001563 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001564 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001565 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001566 Current = ComplexX87;
1567
1568 // If this complex type crosses an eightbyte boundary then it
1569 // should be split.
1570 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001571 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001572 if (Hi == NoClass && EB_Real != EB_Imag)
1573 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001574
Chris Lattnerd776fb12010-06-28 21:43:59 +00001575 return;
1576 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001577
Chris Lattner2b037972010-07-29 02:01:43 +00001578 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001579 // Arrays are treated like structures.
1580
Chris Lattner2b037972010-07-29 02:01:43 +00001581 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001582
1583 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001584 // than four eightbytes, ..., it has class MEMORY.
1585 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001586 return;
1587
1588 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1589 // fields, it has class MEMORY.
1590 //
1591 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001592 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001593 return;
1594
1595 // Otherwise implement simplified merge. We could be smarter about
1596 // this, but it isn't worth it and would be harder to verify.
1597 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001598 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001599 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001600
1601 // The only case a 256-bit wide vector could be used is when the array
1602 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1603 // to work for sizes wider than 128, early check and fallback to memory.
1604 if (Size > 128 && EltSize != 256)
1605 return;
1606
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001607 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1608 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001609 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001610 Lo = merge(Lo, FieldLo);
1611 Hi = merge(Hi, FieldHi);
1612 if (Lo == Memory || Hi == Memory)
1613 break;
1614 }
1615
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001616 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001617 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001618 return;
1619 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001620
Chris Lattnerd776fb12010-06-28 21:43:59 +00001621 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001622 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001623
1624 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001625 // than four eightbytes, ..., it has class MEMORY.
1626 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001627 return;
1628
Anders Carlsson20759ad2009-09-16 15:53:40 +00001629 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1630 // copy constructor or a non-trivial destructor, it is passed by invisible
1631 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001632 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001633 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001634
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001635 const RecordDecl *RD = RT->getDecl();
1636
1637 // Assume variable sized types are passed in memory.
1638 if (RD->hasFlexibleArrayMember())
1639 return;
1640
Chris Lattner2b037972010-07-29 02:01:43 +00001641 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001642
1643 // Reset Lo class, this will be recomputed.
1644 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001645
1646 // If this is a C++ record, classify the bases first.
1647 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1648 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1649 e = CXXRD->bases_end(); i != e; ++i) {
1650 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1651 "Unexpected base class!");
1652 const CXXRecordDecl *Base =
1653 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1654
1655 // Classify this field.
1656 //
1657 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1658 // single eightbyte, each is classified separately. Each eightbyte gets
1659 // initialized to class NO_CLASS.
1660 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001661 uint64_t Offset =
1662 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman96fd2642013-06-12 00:13:45 +00001663 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001664 Lo = merge(Lo, FieldLo);
1665 Hi = merge(Hi, FieldHi);
1666 if (Lo == Memory || Hi == Memory)
1667 break;
1668 }
1669 }
1670
1671 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001672 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001673 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001674 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001675 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1676 bool BitField = i->isBitField();
1677
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001678 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1679 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001680 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001681 // The only case a 256-bit wide vector could be used is when the struct
1682 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1683 // to work for sizes wider than 128, early check and fallback to memory.
1684 //
1685 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1686 Lo = Memory;
1687 return;
1688 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001689 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001690 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001691 Lo = Memory;
1692 return;
1693 }
1694
1695 // Classify this field.
1696 //
1697 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1698 // exceeds a single eightbyte, each is classified
1699 // separately. Each eightbyte gets initialized to class
1700 // NO_CLASS.
1701 Class FieldLo, FieldHi;
1702
1703 // Bit-fields require special handling, they do not force the
1704 // structure to be passed in memory even if unaligned, and
1705 // therefore they can straddle an eightbyte.
1706 if (BitField) {
1707 // Ignore padding bit-fields.
1708 if (i->isUnnamedBitfield())
1709 continue;
1710
1711 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001712 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001713
1714 uint64_t EB_Lo = Offset / 64;
1715 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001716
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001717 if (EB_Lo) {
1718 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1719 FieldLo = NoClass;
1720 FieldHi = Integer;
1721 } else {
1722 FieldLo = Integer;
1723 FieldHi = EB_Hi ? Integer : NoClass;
1724 }
1725 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001726 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001727 Lo = merge(Lo, FieldLo);
1728 Hi = merge(Hi, FieldHi);
1729 if (Lo == Memory || Hi == Memory)
1730 break;
1731 }
1732
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001733 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001734 }
1735}
1736
Chris Lattner22a931e2010-06-29 06:01:59 +00001737ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001738 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1739 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001740 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001741 // Treat an enum type as its underlying type.
1742 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1743 Ty = EnumTy->getDecl()->getIntegerType();
1744
1745 return (Ty->isPromotableIntegerType() ?
1746 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1747 }
1748
1749 return ABIArgInfo::getIndirect(0);
1750}
1751
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001752bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1753 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1754 uint64_t Size = getContext().getTypeSize(VecTy);
1755 unsigned LargestVector = HasAVX ? 256 : 128;
1756 if (Size <= 64 || Size > LargestVector)
1757 return true;
1758 }
1759
1760 return false;
1761}
1762
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001763ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1764 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001765 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1766 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001767 //
1768 // This assumption is optimistic, as there could be free registers available
1769 // when we need to pass this argument in memory, and LLVM could try to pass
1770 // the argument in the free register. This does not seem to happen currently,
1771 // but this code would be much safer if we could mark the argument with
1772 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001773 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001774 // Treat an enum type as its underlying type.
1775 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1776 Ty = EnumTy->getDecl()->getIntegerType();
1777
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001778 return (Ty->isPromotableIntegerType() ?
1779 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001780 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001781
Mark Lacey3825e832013-10-06 01:33:34 +00001782 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001783 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001784
Chris Lattner44c2b902011-05-22 23:21:23 +00001785 // Compute the byval alignment. We specify the alignment of the byval in all
1786 // cases so that the mid-level optimizer knows the alignment of the byval.
1787 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001788
1789 // Attempt to avoid passing indirect results using byval when possible. This
1790 // is important for good codegen.
1791 //
1792 // We do this by coercing the value into a scalar type which the backend can
1793 // handle naturally (i.e., without using byval).
1794 //
1795 // For simplicity, we currently only do this when we have exhausted all of the
1796 // free integer registers. Doing this when there are free integer registers
1797 // would require more care, as we would have to ensure that the coerced value
1798 // did not claim the unused register. That would require either reording the
1799 // arguments to the function (so that any subsequent inreg values came first),
1800 // or only doing this optimization when there were no following arguments that
1801 // might be inreg.
1802 //
1803 // We currently expect it to be rare (particularly in well written code) for
1804 // arguments to be passed on the stack when there are still free integer
1805 // registers available (this would typically imply large structs being passed
1806 // by value), so this seems like a fair tradeoff for now.
1807 //
1808 // We can revisit this if the backend grows support for 'onstack' parameter
1809 // attributes. See PR12193.
1810 if (freeIntRegs == 0) {
1811 uint64_t Size = getContext().getTypeSize(Ty);
1812
1813 // If this type fits in an eightbyte, coerce it into the matching integral
1814 // type, which will end up on the stack (with alignment 8).
1815 if (Align == 8 && Size <= 64)
1816 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1817 Size));
1818 }
1819
Chris Lattner44c2b902011-05-22 23:21:23 +00001820 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001821}
1822
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001823/// GetByteVectorType - The ABI specifies that a value should be passed in an
1824/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001825/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001826llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001827 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001828
Chris Lattner9fa15c32010-07-29 05:02:29 +00001829 // Wrapper structs that just contain vectors are passed just like vectors,
1830 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001831 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001832 while (STy && STy->getNumElements() == 1) {
1833 IRType = STy->getElementType(0);
1834 STy = dyn_cast<llvm::StructType>(IRType);
1835 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001836
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001837 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001838 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1839 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001840 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001841 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001842 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1843 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1844 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1845 EltTy->isIntegerTy(128)))
1846 return VT;
1847 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001848
Chris Lattner4200fe42010-07-29 04:56:46 +00001849 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1850}
1851
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001852/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1853/// is known to either be off the end of the specified type or being in
1854/// alignment padding. The user type specified is known to be at most 128 bits
1855/// in size, and have passed through X86_64ABIInfo::classify with a successful
1856/// classification that put one of the two halves in the INTEGER class.
1857///
1858/// It is conservatively correct to return false.
1859static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1860 unsigned EndBit, ASTContext &Context) {
1861 // If the bytes being queried are off the end of the type, there is no user
1862 // data hiding here. This handles analysis of builtins, vectors and other
1863 // types that don't contain interesting padding.
1864 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1865 if (TySize <= StartBit)
1866 return true;
1867
Chris Lattner98076a22010-07-29 07:43:55 +00001868 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1869 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1870 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1871
1872 // Check each element to see if the element overlaps with the queried range.
1873 for (unsigned i = 0; i != NumElts; ++i) {
1874 // If the element is after the span we care about, then we're done..
1875 unsigned EltOffset = i*EltSize;
1876 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001877
Chris Lattner98076a22010-07-29 07:43:55 +00001878 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1879 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1880 EndBit-EltOffset, Context))
1881 return false;
1882 }
1883 // If it overlaps no elements, then it is safe to process as padding.
1884 return true;
1885 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001886
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001887 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1888 const RecordDecl *RD = RT->getDecl();
1889 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001890
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001891 // If this is a C++ record, check the bases first.
1892 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1893 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1894 e = CXXRD->bases_end(); i != e; ++i) {
1895 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1896 "Unexpected base class!");
1897 const CXXRecordDecl *Base =
1898 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001899
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001900 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001901 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001902 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001903
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001904 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1905 if (!BitsContainNoUserData(i->getType(), BaseStart,
1906 EndBit-BaseOffset, Context))
1907 return false;
1908 }
1909 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001910
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001911 // Verify that no field has data that overlaps the region of interest. Yes
1912 // this could be sped up a lot by being smarter about queried fields,
1913 // however we're only looking at structs up to 16 bytes, so we don't care
1914 // much.
1915 unsigned idx = 0;
1916 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1917 i != e; ++i, ++idx) {
1918 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001919
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001920 // If we found a field after the region we care about, then we're done.
1921 if (FieldOffset >= EndBit) break;
1922
1923 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1924 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1925 Context))
1926 return false;
1927 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001928
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001929 // If nothing in this record overlapped the area of interest, then we're
1930 // clean.
1931 return true;
1932 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001933
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001934 return false;
1935}
1936
Chris Lattnere556a712010-07-29 18:39:32 +00001937/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1938/// float member at the specified offset. For example, {int,{float}} has a
1939/// float at offset 4. It is conservatively correct for this routine to return
1940/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00001941static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001942 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00001943 // Base case if we find a float.
1944 if (IROffset == 0 && IRType->isFloatTy())
1945 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001946
Chris Lattnere556a712010-07-29 18:39:32 +00001947 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001948 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00001949 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1950 unsigned Elt = SL->getElementContainingOffset(IROffset);
1951 IROffset -= SL->getElementOffset(Elt);
1952 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1953 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001954
Chris Lattnere556a712010-07-29 18:39:32 +00001955 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001956 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1957 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00001958 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1959 IROffset -= IROffset/EltSize*EltSize;
1960 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1961 }
1962
1963 return false;
1964}
1965
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001966
1967/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1968/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001969llvm::Type *X86_64ABIInfo::
1970GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001971 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00001972 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001973 // pass as float if the last 4 bytes is just padding. This happens for
1974 // structs that contain 3 floats.
1975 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1976 SourceOffset*8+64, getContext()))
1977 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001978
Chris Lattnere556a712010-07-29 18:39:32 +00001979 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1980 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1981 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00001982 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1983 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00001984 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001985
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001986 return llvm::Type::getDoubleTy(getVMContext());
1987}
1988
1989
Chris Lattner1c56d9a2010-07-29 17:40:35 +00001990/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1991/// an 8-byte GPR. This means that we either have a scalar or we are talking
1992/// about the high or low part of an up-to-16-byte struct. This routine picks
1993/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00001994/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1995/// etc).
1996///
1997/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1998/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1999/// the 8-byte value references. PrefType may be null.
2000///
2001/// SourceTy is the source level type for the entire argument. SourceOffset is
2002/// an offset into this that we're processing (which is always either 0 or 8).
2003///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002004llvm::Type *X86_64ABIInfo::
2005GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002006 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002007 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2008 // returning an 8-byte unit starting with it. See if we can safely use it.
2009 if (IROffset == 0) {
2010 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002011 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2012 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002013 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002014
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002015 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2016 // goodness in the source type is just tail padding. This is allowed to
2017 // kick in for struct {double,int} on the int, but not on
2018 // struct{double,int,int} because we wouldn't return the second int. We
2019 // have to do this analysis on the source type because we can't depend on
2020 // unions being lowered a specific way etc.
2021 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002022 IRType->isIntegerTy(32) ||
2023 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2024 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2025 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002026
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002027 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2028 SourceOffset*8+64, getContext()))
2029 return IRType;
2030 }
2031 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002032
Chris Lattner2192fe52011-07-18 04:24:23 +00002033 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002034 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002035 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002036 if (IROffset < SL->getSizeInBytes()) {
2037 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2038 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002039
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002040 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2041 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002042 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002043 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002044
Chris Lattner2192fe52011-07-18 04:24:23 +00002045 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002046 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002047 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002048 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002049 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2050 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002051 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002052
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002053 // Okay, we don't have any better idea of what to pass, so we pass this in an
2054 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002055 unsigned TySizeInBytes =
2056 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002057
Chris Lattner3f763422010-07-29 17:34:39 +00002058 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002059
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002060 // It is always safe to classify this as an integer type up to i64 that
2061 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002062 return llvm::IntegerType::get(getVMContext(),
2063 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002064}
2065
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002066
2067/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2068/// be used as elements of a two register pair to pass or return, return a
2069/// first class aggregate to represent them. For example, if the low part of
2070/// a by-value argument should be passed as i32* and the high part as float,
2071/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002072static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002073GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002074 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002075 // In order to correctly satisfy the ABI, we need to the high part to start
2076 // at offset 8. If the high and low parts we inferred are both 4-byte types
2077 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2078 // the second element at offset 8. Check for this:
2079 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2080 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002081 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002082 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002083
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002084 // To handle this, we have to increase the size of the low part so that the
2085 // second element will start at an 8 byte offset. We can't increase the size
2086 // of the second element because it might make us access off the end of the
2087 // struct.
2088 if (HiStart != 8) {
2089 // There are only two sorts of types the ABI generation code can produce for
2090 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2091 // Promote these to a larger type.
2092 if (Lo->isFloatTy())
2093 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2094 else {
2095 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2096 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2097 }
2098 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002099
Chris Lattnera5f58b02011-07-09 17:41:47 +00002100 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002101
2102
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002103 // Verify that the second element is at an 8-byte offset.
2104 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2105 "Invalid x86-64 argument pair!");
2106 return Result;
2107}
2108
Chris Lattner31faff52010-07-28 23:06:14 +00002109ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002110classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002111 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2112 // classification algorithm.
2113 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002114 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002115
2116 // Check some invariants.
2117 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002118 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2119
Chris Lattnera5f58b02011-07-09 17:41:47 +00002120 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002121 switch (Lo) {
2122 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002123 if (Hi == NoClass)
2124 return ABIArgInfo::getIgnore();
2125 // If the low part is just padding, it takes no register, leave ResType
2126 // null.
2127 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2128 "Unknown missing lo part");
2129 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002130
2131 case SSEUp:
2132 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002133 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002134
2135 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2136 // hidden argument.
2137 case Memory:
2138 return getIndirectReturnResult(RetTy);
2139
2140 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2141 // available register of the sequence %rax, %rdx is used.
2142 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002143 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002144
Chris Lattner1f3a0632010-07-29 21:42:50 +00002145 // If we have a sign or zero extended integer, make sure to return Extend
2146 // so that the parameter gets the right LLVM IR attributes.
2147 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2148 // Treat an enum type as its underlying type.
2149 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2150 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002151
Chris Lattner1f3a0632010-07-29 21:42:50 +00002152 if (RetTy->isIntegralOrEnumerationType() &&
2153 RetTy->isPromotableIntegerType())
2154 return ABIArgInfo::getExtend();
2155 }
Chris Lattner31faff52010-07-28 23:06:14 +00002156 break;
2157
2158 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2159 // available SSE register of the sequence %xmm0, %xmm1 is used.
2160 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002161 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002162 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002163
2164 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2165 // returned on the X87 stack in %st0 as 80-bit x87 number.
2166 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002167 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002168 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002169
2170 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2171 // part of the value is returned in %st0 and the imaginary part in
2172 // %st1.
2173 case ComplexX87:
2174 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002175 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002176 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002177 NULL);
2178 break;
2179 }
2180
Chris Lattnera5f58b02011-07-09 17:41:47 +00002181 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002182 switch (Hi) {
2183 // Memory was handled previously and X87 should
2184 // never occur as a hi class.
2185 case Memory:
2186 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002187 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002188
2189 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002190 case NoClass:
2191 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002192
Chris Lattner52b3c132010-09-01 00:20:33 +00002193 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002194 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002195 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2196 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002197 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002198 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002199 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002200 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2201 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002202 break;
2203
2204 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002205 // is passed in the next available eightbyte chunk if the last used
2206 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002207 //
Chris Lattner57540c52011-04-15 05:22:18 +00002208 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002209 case SSEUp:
2210 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002211 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002212 break;
2213
2214 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2215 // returned together with the previous X87 value in %st0.
2216 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002217 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002218 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002219 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002220 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002221 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002222 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002223 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2224 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002225 }
Chris Lattner31faff52010-07-28 23:06:14 +00002226 break;
2227 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002228
Chris Lattner52b3c132010-09-01 00:20:33 +00002229 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002230 // known to pass in the high eightbyte of the result. We do this by forming a
2231 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002232 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002233 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002234
Chris Lattner1f3a0632010-07-29 21:42:50 +00002235 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002236}
2237
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002238ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002239 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2240 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002241 const
2242{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002243 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002244 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002245
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002246 // Check some invariants.
2247 // FIXME: Enforce these by construction.
2248 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002249 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2250
2251 neededInt = 0;
2252 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002253 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002254 switch (Lo) {
2255 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002256 if (Hi == NoClass)
2257 return ABIArgInfo::getIgnore();
2258 // If the low part is just padding, it takes no register, leave ResType
2259 // null.
2260 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2261 "Unknown missing lo part");
2262 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002263
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002264 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2265 // on the stack.
2266 case Memory:
2267
2268 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2269 // COMPLEX_X87, it is passed in memory.
2270 case X87:
2271 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002272 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002273 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002274 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002275
2276 case SSEUp:
2277 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002278 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002279
2280 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2281 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2282 // and %r9 is used.
2283 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002284 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002285
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002286 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002287 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002288
2289 // If we have a sign or zero extended integer, make sure to return Extend
2290 // so that the parameter gets the right LLVM IR attributes.
2291 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2292 // Treat an enum type as its underlying type.
2293 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2294 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002295
Chris Lattner1f3a0632010-07-29 21:42:50 +00002296 if (Ty->isIntegralOrEnumerationType() &&
2297 Ty->isPromotableIntegerType())
2298 return ABIArgInfo::getExtend();
2299 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002300
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002301 break;
2302
2303 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2304 // available SSE register is used, the registers are taken in the
2305 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002306 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002307 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002308 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002309 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002310 break;
2311 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002312 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002313
Chris Lattnera5f58b02011-07-09 17:41:47 +00002314 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002315 switch (Hi) {
2316 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002317 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002318 // which is passed in memory.
2319 case Memory:
2320 case X87:
2321 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002322 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002323
2324 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002325
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002326 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002327 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002328 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002329 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002330
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002331 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2332 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002333 break;
2334
2335 // X87Up generally doesn't occur here (long double is passed in
2336 // memory), except in situations involving unions.
2337 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002338 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002339 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002340
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002341 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2342 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002343
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002344 ++neededSSE;
2345 break;
2346
2347 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2348 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002349 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002350 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002351 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002352 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002353 break;
2354 }
2355
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002356 // If a high part was specified, merge it together with the low part. It is
2357 // known to pass in the high eightbyte of the result. We do this by forming a
2358 // first class struct aggregate with the high and low part: {low, high}
2359 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002360 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002361
Chris Lattner1f3a0632010-07-29 21:42:50 +00002362 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002363}
2364
Chris Lattner22326a12010-07-29 02:31:05 +00002365void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002366
Chris Lattner458b2aa2010-07-29 02:16:43 +00002367 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002368
2369 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002370 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002371
2372 // If the return value is indirect, then the hidden argument is consuming one
2373 // integer register.
2374 if (FI.getReturnInfo().isIndirect())
2375 --freeIntRegs;
2376
Eli Friedman96fd2642013-06-12 00:13:45 +00002377 bool isVariadic = FI.isVariadic();
2378 unsigned numRequiredArgs = 0;
2379 if (isVariadic)
2380 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2381
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002382 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2383 // get assigned (in left-to-right order) for passing as follows...
2384 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2385 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002386 bool isNamedArg = true;
2387 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002388 isNamedArg = (it - FI.arg_begin()) <
2389 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002390
Bill Wendling9987c0e2010-10-18 23:51:38 +00002391 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002392 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002393 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002394
2395 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2396 // eightbyte of an argument, the whole argument is passed on the
2397 // stack. If registers have already been assigned for some
2398 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002399 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002400 freeIntRegs -= neededInt;
2401 freeSSERegs -= neededSSE;
2402 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002403 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002404 }
2405 }
2406}
2407
2408static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2409 QualType Ty,
2410 CodeGenFunction &CGF) {
2411 llvm::Value *overflow_arg_area_p =
2412 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2413 llvm::Value *overflow_arg_area =
2414 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2415
2416 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2417 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002418 // It isn't stated explicitly in the standard, but in practice we use
2419 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002420 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2421 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002422 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002423 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002424 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2426 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002427 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002428 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002429 overflow_arg_area =
2430 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2431 overflow_arg_area->getType(),
2432 "overflow_arg_area.align");
2433 }
2434
2435 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002436 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002437 llvm::Value *Res =
2438 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002439 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002440
2441 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2442 // l->overflow_arg_area + sizeof(type).
2443 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2444 // an 8 byte boundary.
2445
2446 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002447 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002448 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002449 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2450 "overflow_arg_area.next");
2451 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2452
2453 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2454 return Res;
2455}
2456
2457llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2458 CodeGenFunction &CGF) const {
2459 // Assume that va_list type is correct; should be pointer to LLVM type:
2460 // struct {
2461 // i32 gp_offset;
2462 // i32 fp_offset;
2463 // i8* overflow_arg_area;
2464 // i8* reg_save_area;
2465 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002466 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002467
Chris Lattner9723d6c2010-03-11 18:19:55 +00002468 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002469 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2470 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002471
2472 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2473 // in the registers. If not go to step 7.
2474 if (!neededInt && !neededSSE)
2475 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2476
2477 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2478 // general purpose registers needed to pass type and num_fp to hold
2479 // the number of floating point registers needed.
2480
2481 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2482 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2483 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2484 //
2485 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2486 // register save space).
2487
2488 llvm::Value *InRegs = 0;
2489 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2490 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2491 if (neededInt) {
2492 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2493 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002494 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2495 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496 }
2497
2498 if (neededSSE) {
2499 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2500 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2501 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002502 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2503 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002504 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2505 }
2506
2507 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2508 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2509 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2510 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2511
2512 // Emit code to load the value if it was passed in registers.
2513
2514 CGF.EmitBlock(InRegBlock);
2515
2516 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2517 // an offset of l->gp_offset and/or l->fp_offset. This may require
2518 // copying to a temporary location in case the parameter is passed
2519 // in different register classes or requires an alignment greater
2520 // than 8 for general purpose registers and 16 for XMM registers.
2521 //
2522 // FIXME: This really results in shameful code when we end up needing to
2523 // collect arguments from different places; often what should result in a
2524 // simple assembling of a structure from scattered addresses has many more
2525 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002526 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 llvm::Value *RegAddr =
2528 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2529 "reg_save_area");
2530 if (neededInt && neededSSE) {
2531 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002532 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002533 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002534 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2535 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002536 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002537 llvm::Type *TyLo = ST->getElementType(0);
2538 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002539 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002540 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002541 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2542 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002543 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2544 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002545 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2546 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002547 llvm::Value *V =
2548 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2549 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2550 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2551 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2552
Owen Anderson170229f2009-07-14 23:10:40 +00002553 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002554 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 } else if (neededInt) {
2556 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2557 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002558 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002559
2560 // Copy to a temporary if necessary to ensure the appropriate alignment.
2561 std::pair<CharUnits, CharUnits> SizeAlign =
2562 CGF.getContext().getTypeInfoInChars(Ty);
2563 uint64_t TySize = SizeAlign.first.getQuantity();
2564 unsigned TyAlign = SizeAlign.second.getQuantity();
2565 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002566 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2567 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2568 RegAddr = Tmp;
2569 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002570 } else if (neededSSE == 1) {
2571 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2572 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2573 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002574 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002575 assert(neededSSE == 2 && "Invalid number of needed registers!");
2576 // SSE registers are spaced 16 bytes apart in the register save
2577 // area, we need to collect the two eightbytes together.
2578 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002579 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002580 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002581 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002582 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002583 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2584 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2585 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002586 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2587 DblPtrTy));
2588 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2589 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2590 DblPtrTy));
2591 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2592 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2593 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002594 }
2595
2596 // AMD64-ABI 3.5.7p5: Step 5. Set:
2597 // l->gp_offset = l->gp_offset + num_gp * 8
2598 // l->fp_offset = l->fp_offset + num_fp * 16.
2599 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002600 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002601 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2602 gp_offset_p);
2603 }
2604 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002605 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002606 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2607 fp_offset_p);
2608 }
2609 CGF.EmitBranch(ContBlock);
2610
2611 // Emit code to load the value if it was passed in memory.
2612
2613 CGF.EmitBlock(InMemBlock);
2614 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2615
2616 // Return the appropriate result.
2617
2618 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002619 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 ResAddr->addIncoming(RegAddr, InRegBlock);
2622 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002623 return ResAddr;
2624}
2625
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002626ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002627
2628 if (Ty->isVoidType())
2629 return ABIArgInfo::getIgnore();
2630
2631 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2632 Ty = EnumTy->getDecl()->getIntegerType();
2633
2634 uint64_t Size = getContext().getTypeSize(Ty);
2635
2636 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002637 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002638 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002639 return ABIArgInfo::getIndirect(0, false);
2640 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002641 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002642 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2643 }
2644
2645 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002646 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2647
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002648 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002649 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002650 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2651 Size));
2652
2653 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2654 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2655 if (Size <= 64 &&
NAKAMURA Takumie03c6032011-01-19 00:11:33 +00002656 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002657 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2658 Size));
2659
2660 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2661 }
2662
2663 if (Ty->isPromotableIntegerType())
2664 return ABIArgInfo::getExtend();
2665
2666 return ABIArgInfo::getDirect();
2667}
2668
2669void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2670
2671 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002672 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002673
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002674 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2675 it != ie; ++it)
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002676 it->info = classify(it->type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002677}
2678
Chris Lattner04dc9572010-08-31 16:44:54 +00002679llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2680 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002681 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002682
Chris Lattner04dc9572010-08-31 16:44:54 +00002683 CGBuilderTy &Builder = CGF.Builder;
2684 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2685 "ap");
2686 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2687 llvm::Type *PTy =
2688 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2689 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2690
2691 uint64_t Offset =
2692 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2693 llvm::Value *NextAddr =
2694 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2695 "ap.next");
2696 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2697
2698 return AddrTyped;
2699}
Chris Lattner0cf24192010-06-28 20:05:43 +00002700
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002701namespace {
2702
Derek Schuffa2020962012-10-16 22:30:41 +00002703class NaClX86_64ABIInfo : public ABIInfo {
2704 public:
2705 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2706 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2707 virtual void computeInfo(CGFunctionInfo &FI) const;
2708 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2709 CodeGenFunction &CGF) const;
2710 private:
2711 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2712 X86_64ABIInfo NInfo; // Used for everything else.
2713};
2714
2715class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2716 public:
2717 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2718 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2719};
2720
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002721}
2722
Derek Schuffa2020962012-10-16 22:30:41 +00002723void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2724 if (FI.getASTCallingConvention() == CC_PnaclCall)
2725 PInfo.computeInfo(FI);
2726 else
2727 NInfo.computeInfo(FI);
2728}
2729
2730llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2731 CodeGenFunction &CGF) const {
2732 // Always use the native convention; calling pnacl-style varargs functions
2733 // is unuspported.
2734 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2735}
2736
2737
John McCallea8d8bb2010-03-11 00:10:12 +00002738// PowerPC-32
2739
2740namespace {
2741class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2742public:
Chris Lattner2b037972010-07-29 02:01:43 +00002743 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002744
John McCallea8d8bb2010-03-11 00:10:12 +00002745 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2746 // This is recovered from gcc output.
2747 return 1; // r1 is the dedicated stack pointer
2748 }
2749
2750 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002751 llvm::Value *Address) const;
John McCallea8d8bb2010-03-11 00:10:12 +00002752};
2753
2754}
2755
2756bool
2757PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2758 llvm::Value *Address) const {
2759 // This is calculated from the LLVM and GCC tables and verified
2760 // against gcc output. AFAIK all ABIs use the same encoding.
2761
2762 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002763
Chris Lattnerece04092012-02-07 00:39:47 +00002764 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002765 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2766 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2767 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2768
2769 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002770 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002771
2772 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002773 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002774
2775 // 64-76 are various 4-byte special-purpose registers:
2776 // 64: mq
2777 // 65: lr
2778 // 66: ctr
2779 // 67: ap
2780 // 68-75 cr0-7
2781 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002782 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002783
2784 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002785 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002786
2787 // 109: vrsave
2788 // 110: vscr
2789 // 111: spe_acc
2790 // 112: spefscr
2791 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002792 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002793
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002794 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002795}
2796
Roman Divackyd966e722012-05-09 18:22:46 +00002797// PowerPC-64
2798
2799namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002800/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2801class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2802
2803public:
2804 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2805
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002806 bool isPromotableTypeForABI(QualType Ty) const;
2807
2808 ABIArgInfo classifyReturnType(QualType RetTy) const;
2809 ABIArgInfo classifyArgumentType(QualType Ty) const;
2810
Bill Schmidt84d37792012-10-12 19:26:17 +00002811 // TODO: We can add more logic to computeInfo to improve performance.
2812 // Example: For aggregate arguments that fit in a register, we could
2813 // use getDirectInReg (as is done below for structs containing a single
2814 // floating-point value) to avoid pushing them to memory on function
2815 // entry. This would require changing the logic in PPCISelLowering
2816 // when lowering the parameters in the caller and args in the callee.
2817 virtual void computeInfo(CGFunctionInfo &FI) const {
2818 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2819 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2820 it != ie; ++it) {
2821 // We rely on the default argument classification for the most part.
2822 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002823 // or vector item must be passed in a register if one is available.
Bill Schmidt84d37792012-10-12 19:26:17 +00002824 const Type *T = isSingleElementStruct(it->type, getContext());
2825 if (T) {
2826 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002827 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002828 QualType QT(T, 0);
2829 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2830 continue;
2831 }
2832 }
2833 it->info = classifyArgumentType(it->type);
2834 }
2835 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002836
2837 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2838 QualType Ty,
2839 CodeGenFunction &CGF) const;
2840};
2841
2842class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2843public:
2844 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2845 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2846
2847 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2848 // This is recovered from gcc output.
2849 return 1; // r1 is the dedicated stack pointer
2850 }
2851
2852 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2853 llvm::Value *Address) const;
2854};
2855
Roman Divackyd966e722012-05-09 18:22:46 +00002856class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2857public:
2858 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2859
2860 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2861 // This is recovered from gcc output.
2862 return 1; // r1 is the dedicated stack pointer
2863 }
2864
2865 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2866 llvm::Value *Address) const;
2867};
2868
2869}
2870
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002871// Return true if the ABI requires Ty to be passed sign- or zero-
2872// extended to 64 bits.
2873bool
2874PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2875 // Treat an enum type as its underlying type.
2876 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2877 Ty = EnumTy->getDecl()->getIntegerType();
2878
2879 // Promotable integer types are required to be promoted by the ABI.
2880 if (Ty->isPromotableIntegerType())
2881 return true;
2882
2883 // In addition to the usual promotable integer types, we also need to
2884 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2885 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2886 switch (BT->getKind()) {
2887 case BuiltinType::Int:
2888 case BuiltinType::UInt:
2889 return true;
2890 default:
2891 break;
2892 }
2893
2894 return false;
2895}
2896
2897ABIArgInfo
2898PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002899 if (Ty->isAnyComplexType())
2900 return ABIArgInfo::getDirect();
2901
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002902 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002903 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002904 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002905
2906 return ABIArgInfo::getIndirect(0);
2907 }
2908
2909 return (isPromotableTypeForABI(Ty) ?
2910 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2911}
2912
2913ABIArgInfo
2914PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2915 if (RetTy->isVoidType())
2916 return ABIArgInfo::getIgnore();
2917
Bill Schmidta3d121c2012-12-17 04:20:17 +00002918 if (RetTy->isAnyComplexType())
2919 return ABIArgInfo::getDirect();
2920
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002921 if (isAggregateTypeForABI(RetTy))
2922 return ABIArgInfo::getIndirect(0);
2923
2924 return (isPromotableTypeForABI(RetTy) ?
2925 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2926}
2927
Bill Schmidt25cb3492012-10-03 19:18:57 +00002928// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2929llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2930 QualType Ty,
2931 CodeGenFunction &CGF) const {
2932 llvm::Type *BP = CGF.Int8PtrTy;
2933 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2934
2935 CGBuilderTy &Builder = CGF.Builder;
2936 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2937 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2938
Bill Schmidt924c4782013-01-14 17:45:36 +00002939 // Update the va_list pointer. The pointer should be bumped by the
2940 // size of the object. We can trust getTypeSize() except for a complex
2941 // type whose base type is smaller than a doubleword. For these, the
2942 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00002943 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00002944 QualType BaseTy;
2945 unsigned CplxBaseSize = 0;
2946
2947 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2948 BaseTy = CTy->getElementType();
2949 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2950 if (CplxBaseSize < 8)
2951 SizeInBytes = 16;
2952 }
2953
Bill Schmidt25cb3492012-10-03 19:18:57 +00002954 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2955 llvm::Value *NextAddr =
2956 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2957 "ap.next");
2958 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2959
Bill Schmidt924c4782013-01-14 17:45:36 +00002960 // If we have a complex type and the base type is smaller than 8 bytes,
2961 // the ABI calls for the real and imaginary parts to be right-adjusted
2962 // in separate doublewords. However, Clang expects us to produce a
2963 // pointer to a structure with the two parts packed tightly. So generate
2964 // loads of the real and imaginary parts relative to the va_list pointer,
2965 // and store them to a temporary structure.
2966 if (CplxBaseSize && CplxBaseSize < 8) {
2967 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2968 llvm::Value *ImagAddr = RealAddr;
2969 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2970 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2971 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2972 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2973 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2974 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2975 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2976 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2977 "vacplx");
2978 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2979 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2980 Builder.CreateStore(Real, RealPtr, false);
2981 Builder.CreateStore(Imag, ImagPtr, false);
2982 return Ptr;
2983 }
2984
Bill Schmidt25cb3492012-10-03 19:18:57 +00002985 // If the argument is smaller than 8 bytes, it is right-adjusted in
2986 // its doubleword slot. Adjust the pointer to pick it up from the
2987 // correct offset.
2988 if (SizeInBytes < 8) {
2989 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2990 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2991 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2992 }
2993
2994 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2995 return Builder.CreateBitCast(Addr, PTy);
2996}
2997
2998static bool
2999PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3000 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003001 // This is calculated from the LLVM and GCC tables and verified
3002 // against gcc output. AFAIK all ABIs use the same encoding.
3003
3004 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3005
3006 llvm::IntegerType *i8 = CGF.Int8Ty;
3007 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3008 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3009 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3010
3011 // 0-31: r0-31, the 8-byte general-purpose registers
3012 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3013
3014 // 32-63: fp0-31, the 8-byte floating-point registers
3015 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3016
3017 // 64-76 are various 4-byte special-purpose registers:
3018 // 64: mq
3019 // 65: lr
3020 // 66: ctr
3021 // 67: ap
3022 // 68-75 cr0-7
3023 // 76: xer
3024 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3025
3026 // 77-108: v0-31, the 16-byte vector registers
3027 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3028
3029 // 109: vrsave
3030 // 110: vscr
3031 // 111: spe_acc
3032 // 112: spefscr
3033 // 113: sfp
3034 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3035
3036 return false;
3037}
John McCallea8d8bb2010-03-11 00:10:12 +00003038
Bill Schmidt25cb3492012-10-03 19:18:57 +00003039bool
3040PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3041 CodeGen::CodeGenFunction &CGF,
3042 llvm::Value *Address) const {
3043
3044 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3045}
3046
3047bool
3048PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3049 llvm::Value *Address) const {
3050
3051 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3052}
3053
Chris Lattner0cf24192010-06-28 20:05:43 +00003054//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003055// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003056//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003057
3058namespace {
3059
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003060class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003061public:
3062 enum ABIKind {
3063 APCS = 0,
3064 AAPCS = 1,
3065 AAPCS_VFP
3066 };
3067
3068private:
3069 ABIKind Kind;
3070
3071public:
John McCall882987f2013-02-28 19:01:20 +00003072 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3073 setRuntimeCC();
3074 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003075
John McCall3480ef22011-08-30 01:42:09 +00003076 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003077 switch (getTarget().getTriple().getEnvironment()) {
3078 case llvm::Triple::Android:
3079 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003080 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003081 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003082 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003083 return true;
3084 default:
3085 return false;
3086 }
John McCall3480ef22011-08-30 01:42:09 +00003087 }
3088
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003089 bool isEABIHF() const {
3090 switch (getTarget().getTriple().getEnvironment()) {
3091 case llvm::Triple::EABIHF:
3092 case llvm::Triple::GNUEABIHF:
3093 return true;
3094 default:
3095 return false;
3096 }
3097 }
3098
Daniel Dunbar020daa92009-09-12 01:00:39 +00003099 ABIKind getABIKind() const { return Kind; }
3100
Tim Northovera484bc02013-10-01 14:34:25 +00003101private:
Chris Lattner458b2aa2010-07-29 02:16:43 +00003102 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Renb505d332012-10-31 19:02:26 +00003103 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3104 unsigned &AllocatedVFP,
Manman Ren2a523d82012-10-30 23:21:41 +00003105 bool &IsHA) const;
Manman Renfef9e312012-10-16 19:18:39 +00003106 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003107
Chris Lattner22326a12010-07-29 02:31:05 +00003108 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003109
3110 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3111 CodeGenFunction &CGF) const;
John McCall882987f2013-02-28 19:01:20 +00003112
3113 llvm::CallingConv::ID getLLVMDefaultCC() const;
3114 llvm::CallingConv::ID getABIDefaultCC() const;
3115 void setRuntimeCC();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003116};
3117
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003118class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3119public:
Chris Lattner2b037972010-07-29 02:01:43 +00003120 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3121 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003122
John McCall3480ef22011-08-30 01:42:09 +00003123 const ARMABIInfo &getABIInfo() const {
3124 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3125 }
3126
John McCallbeec5a02010-03-06 00:35:14 +00003127 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3128 return 13;
3129 }
Roman Divackyc1617352011-05-18 19:36:54 +00003130
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003131 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCall31168b02011-06-15 23:02:42 +00003132 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3133 }
3134
Roman Divackyc1617352011-05-18 19:36:54 +00003135 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3136 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003137 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003138
3139 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003140 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003141 return false;
3142 }
John McCall3480ef22011-08-30 01:42:09 +00003143
3144 unsigned getSizeOfUnwindException() const {
3145 if (getABIInfo().isEABI()) return 88;
3146 return TargetCodeGenInfo::getSizeOfUnwindException();
3147 }
Tim Northovera484bc02013-10-01 14:34:25 +00003148
3149 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3150 CodeGen::CodeGenModule &CGM) const {
3151 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3152 if (!FD)
3153 return;
3154
3155 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3156 if (!Attr)
3157 return;
3158
3159 const char *Kind;
3160 switch (Attr->getInterrupt()) {
3161 case ARMInterruptAttr::Generic: Kind = ""; break;
3162 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3163 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3164 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3165 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3166 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3167 }
3168
3169 llvm::Function *Fn = cast<llvm::Function>(GV);
3170
3171 Fn->addFnAttr("interrupt", Kind);
3172
3173 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3174 return;
3175
3176 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3177 // however this is not necessarily true on taking any interrupt. Instruct
3178 // the backend to perform a realignment as part of the function prologue.
3179 llvm::AttrBuilder B;
3180 B.addStackAlignmentAttr(8);
3181 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3182 llvm::AttributeSet::get(CGM.getLLVMContext(),
3183 llvm::AttributeSet::FunctionIndex,
3184 B));
3185 }
3186
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003187};
3188
Daniel Dunbard59655c2009-09-12 00:59:49 +00003189}
3190
Chris Lattner22326a12010-07-29 02:31:05 +00003191void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003192 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003193 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003194 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3195 // VFP registers of the appropriate type unallocated then the argument is
3196 // allocated to the lowest-numbered sequence of such registers.
3197 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3198 // unallocated are marked as unavailable.
3199 unsigned AllocatedVFP = 0;
Manman Renb505d332012-10-31 19:02:26 +00003200 int VFPRegs[16] = { 0 };
Chris Lattner458b2aa2010-07-29 02:16:43 +00003201 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003202 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Ren2a523d82012-10-30 23:21:41 +00003203 it != ie; ++it) {
3204 unsigned PreAllocation = AllocatedVFP;
3205 bool IsHA = false;
3206 // 6.1.2.3 There is one VFP co-processor register class using registers
3207 // s0-s15 (d0-d7) for passing arguments.
3208 const unsigned NumVFPs = 16;
Manman Renb505d332012-10-31 19:02:26 +00003209 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Ren2a523d82012-10-30 23:21:41 +00003210 // If we do not have enough VFP registers for the HA, any VFP registers
3211 // that are unallocated are marked as unavailable. To achieve this, we add
3212 // padding of (NumVFPs - PreAllocation) floats.
3213 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3214 llvm::Type *PaddingTy = llvm::ArrayType::get(
3215 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3216 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3217 }
3218 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003219
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003220 // Always honor user-specified calling convention.
3221 if (FI.getCallingConvention() != llvm::CallingConv::C)
3222 return;
3223
John McCall882987f2013-02-28 19:01:20 +00003224 llvm::CallingConv::ID cc = getRuntimeCC();
3225 if (cc != llvm::CallingConv::C)
3226 FI.setEffectiveCallingConvention(cc);
3227}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003228
John McCall882987f2013-02-28 19:01:20 +00003229/// Return the default calling convention that LLVM will use.
3230llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3231 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003232 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003233 return llvm::CallingConv::ARM_AAPCS_VFP;
3234 else if (isEABI())
3235 return llvm::CallingConv::ARM_AAPCS;
3236 else
3237 return llvm::CallingConv::ARM_APCS;
3238}
3239
3240/// Return the calling convention that our ABI would like us to use
3241/// as the C calling convention.
3242llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003243 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003244 case APCS: return llvm::CallingConv::ARM_APCS;
3245 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3246 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003247 }
John McCall882987f2013-02-28 19:01:20 +00003248 llvm_unreachable("bad ABI kind");
3249}
3250
3251void ARMABIInfo::setRuntimeCC() {
3252 assert(getRuntimeCC() == llvm::CallingConv::C);
3253
3254 // Don't muddy up the IR with a ton of explicit annotations if
3255 // they'd just match what LLVM will infer from the triple.
3256 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3257 if (abiCC != getLLVMDefaultCC())
3258 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003259}
3260
Bob Wilsone826a2a2011-08-03 05:58:22 +00003261/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3262/// aggregate. If HAMembers is non-null, the number of base elements
3263/// contained in the type is returned through it; this is used for the
3264/// recursive calls that check aggregate component types.
3265static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3266 ASTContext &Context,
3267 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003268 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003269 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3270 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3271 return false;
3272 Members *= AT->getSize().getZExtValue();
3273 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3274 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003275 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003276 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003277
Bob Wilsone826a2a2011-08-03 05:58:22 +00003278 Members = 0;
3279 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3280 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003281 const FieldDecl *FD = *i;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003282 uint64_t FldMembers;
3283 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3284 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003285
3286 Members = (RD->isUnion() ?
3287 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003288 }
3289 } else {
3290 Members = 1;
3291 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3292 Members = 2;
3293 Ty = CT->getElementType();
3294 }
3295
3296 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3297 // double, or 64-bit or 128-bit vectors.
3298 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3299 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003300 BT->getKind() != BuiltinType::Double &&
3301 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003302 return false;
3303 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3304 unsigned VecSize = Context.getTypeSize(VT);
3305 if (VecSize != 64 && VecSize != 128)
3306 return false;
3307 } else {
3308 return false;
3309 }
3310
3311 // The base type must be the same for all members. Vector types of the
3312 // same total size are treated as being equivalent here.
3313 const Type *TyPtr = Ty.getTypePtr();
3314 if (!Base)
3315 Base = TyPtr;
3316 if (Base != TyPtr &&
3317 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3318 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3319 return false;
3320 }
3321
3322 // Homogeneous Aggregates can have at most 4 members of the base type.
3323 if (HAMembers)
3324 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003325
3326 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003327}
3328
Manman Renb505d332012-10-31 19:02:26 +00003329/// markAllocatedVFPs - update VFPRegs according to the alignment and
3330/// number of VFP registers (unit is S register) requested.
3331static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3332 unsigned Alignment,
3333 unsigned NumRequired) {
3334 // Early Exit.
3335 if (AllocatedVFP >= 16)
3336 return;
3337 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3338 // VFP registers of the appropriate type unallocated then the argument is
3339 // allocated to the lowest-numbered sequence of such registers.
3340 for (unsigned I = 0; I < 16; I += Alignment) {
3341 bool FoundSlot = true;
3342 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3343 if (J >= 16 || VFPRegs[J]) {
3344 FoundSlot = false;
3345 break;
3346 }
3347 if (FoundSlot) {
3348 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3349 VFPRegs[J] = 1;
3350 AllocatedVFP += NumRequired;
3351 return;
3352 }
3353 }
3354 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3355 // unallocated are marked as unavailable.
3356 for (unsigned I = 0; I < 16; I++)
3357 VFPRegs[I] = 1;
3358 AllocatedVFP = 17; // We do not have enough VFP registers.
3359}
3360
3361ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3362 unsigned &AllocatedVFP,
Manman Ren2a523d82012-10-30 23:21:41 +00003363 bool &IsHA) const {
3364 // We update number of allocated VFPs according to
3365 // 6.1.2.1 The following argument types are VFP CPRCs:
3366 // A single-precision floating-point type (including promoted
3367 // half-precision types); A double-precision floating-point type;
3368 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3369 // with a Base Type of a single- or double-precision floating-point type,
3370 // 64-bit containerized vectors or 128-bit containerized vectors with one
3371 // to four Elements.
3372
Manman Renfef9e312012-10-16 19:18:39 +00003373 // Handle illegal vector types here.
3374 if (isIllegalVectorType(Ty)) {
3375 uint64_t Size = getContext().getTypeSize(Ty);
3376 if (Size <= 32) {
3377 llvm::Type *ResType =
3378 llvm::Type::getInt32Ty(getVMContext());
3379 return ABIArgInfo::getDirect(ResType);
3380 }
3381 if (Size == 64) {
3382 llvm::Type *ResType = llvm::VectorType::get(
3383 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Renb505d332012-10-31 19:02:26 +00003384 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renfef9e312012-10-16 19:18:39 +00003385 return ABIArgInfo::getDirect(ResType);
3386 }
3387 if (Size == 128) {
3388 llvm::Type *ResType = llvm::VectorType::get(
3389 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Renb505d332012-10-31 19:02:26 +00003390 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Renfef9e312012-10-16 19:18:39 +00003391 return ABIArgInfo::getDirect(ResType);
3392 }
3393 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3394 }
Manman Renb505d332012-10-31 19:02:26 +00003395 // Update VFPRegs for legal vector types.
Manman Ren2a523d82012-10-30 23:21:41 +00003396 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3397 uint64_t Size = getContext().getTypeSize(VT);
3398 // Size of a legal vector should be power of 2 and above 64.
Manman Renb505d332012-10-31 19:02:26 +00003399 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Ren2a523d82012-10-30 23:21:41 +00003400 }
Manman Renb505d332012-10-31 19:02:26 +00003401 // Update VFPRegs for floating point types.
Manman Ren2a523d82012-10-30 23:21:41 +00003402 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3403 if (BT->getKind() == BuiltinType::Half ||
3404 BT->getKind() == BuiltinType::Float)
Manman Renb505d332012-10-31 19:02:26 +00003405 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Ren2a523d82012-10-30 23:21:41 +00003406 if (BT->getKind() == BuiltinType::Double ||
Manman Renb505d332012-10-31 19:02:26 +00003407 BT->getKind() == BuiltinType::LongDouble)
3408 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003409 }
Manman Renfef9e312012-10-16 19:18:39 +00003410
John McCalla1dee5302010-08-22 10:59:02 +00003411 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003412 // Treat an enum type as its underlying type.
3413 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3414 Ty = EnumTy->getDecl()->getIntegerType();
3415
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003416 return (Ty->isPromotableIntegerType() ?
3417 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003418 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003419
Mark Lacey3825e832013-10-06 01:33:34 +00003420 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Tim Northover1060eae2013-06-21 22:49:34 +00003421 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3422
Daniel Dunbar09d33622009-09-14 21:54:03 +00003423 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003424 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003425 return ABIArgInfo::getIgnore();
3426
Bob Wilsone826a2a2011-08-03 05:58:22 +00003427 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00003428 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3429 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003430 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003431 uint64_t Members = 0;
3432 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003433 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003434 // Base can be a floating-point or a vector.
3435 if (Base->isVectorType()) {
3436 // ElementSize is in number of floats.
3437 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Ren77b02382012-11-06 19:05:29 +00003438 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3439 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003440 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Renb505d332012-10-31 19:02:26 +00003441 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003442 else {
3443 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3444 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Renb505d332012-10-31 19:02:26 +00003445 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003446 }
3447 IsHA = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003448 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003449 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003450 }
3451
Manman Ren6c30e132012-08-13 21:23:55 +00003452 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003453 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3454 // most 8-byte. We realign the indirect argument if type alignment is bigger
3455 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003456 uint64_t ABIAlign = 4;
3457 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3458 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3459 getABIKind() == ARMABIInfo::AAPCS)
3460 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003461 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3462 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003463 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003464 }
3465
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003466 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003467 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003468 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003469 // FIXME: Try to match the types of the arguments more accurately where
3470 // we can.
3471 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003472 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3473 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00003474 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003475 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3476 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003477 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003478
Chris Lattnera5f58b02011-07-09 17:41:47 +00003479 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003480 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003481 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003482}
3483
Chris Lattner458b2aa2010-07-29 02:16:43 +00003484static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003485 llvm::LLVMContext &VMContext) {
3486 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3487 // is called integer-like if its size is less than or equal to one word, and
3488 // the offset of each of its addressable sub-fields is zero.
3489
3490 uint64_t Size = Context.getTypeSize(Ty);
3491
3492 // Check that the type fits in a word.
3493 if (Size > 32)
3494 return false;
3495
3496 // FIXME: Handle vector types!
3497 if (Ty->isVectorType())
3498 return false;
3499
Daniel Dunbard53bac72009-09-14 02:20:34 +00003500 // Float types are never treated as "integer like".
3501 if (Ty->isRealFloatingType())
3502 return false;
3503
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003504 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003505 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003506 return true;
3507
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003508 // Small complex integer types are "integer like".
3509 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3510 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003511
3512 // Single element and zero sized arrays should be allowed, by the definition
3513 // above, but they are not.
3514
3515 // Otherwise, it must be a record type.
3516 const RecordType *RT = Ty->getAs<RecordType>();
3517 if (!RT) return false;
3518
3519 // Ignore records with flexible arrays.
3520 const RecordDecl *RD = RT->getDecl();
3521 if (RD->hasFlexibleArrayMember())
3522 return false;
3523
3524 // Check that all sub-fields are at offset 0, and are themselves "integer
3525 // like".
3526 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3527
3528 bool HadField = false;
3529 unsigned idx = 0;
3530 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3531 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003532 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003533
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003534 // Bit-fields are not addressable, we only need to verify they are "integer
3535 // like". We still have to disallow a subsequent non-bitfield, for example:
3536 // struct { int : 0; int x }
3537 // is non-integer like according to gcc.
3538 if (FD->isBitField()) {
3539 if (!RD->isUnion())
3540 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003541
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003542 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3543 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003544
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003545 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003546 }
3547
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003548 // Check if this field is at offset 0.
3549 if (Layout.getFieldOffset(idx) != 0)
3550 return false;
3551
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003552 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3553 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003554
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003555 // Only allow at most one field in a structure. This doesn't match the
3556 // wording above, but follows gcc in situations with a field following an
3557 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003558 if (!RD->isUnion()) {
3559 if (HadField)
3560 return false;
3561
3562 HadField = true;
3563 }
3564 }
3565
3566 return true;
3567}
3568
Chris Lattner458b2aa2010-07-29 02:16:43 +00003569ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003570 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003571 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003572
Daniel Dunbar19964db2010-09-23 01:54:32 +00003573 // Large vector types should be returned via memory.
3574 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3575 return ABIArgInfo::getIndirect(0);
3576
John McCalla1dee5302010-08-22 10:59:02 +00003577 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003578 // Treat an enum type as its underlying type.
3579 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3580 RetTy = EnumTy->getDecl()->getIntegerType();
3581
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003582 return (RetTy->isPromotableIntegerType() ?
3583 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003584 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003585
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003586 // Structures with either a non-trivial destructor or a non-trivial
3587 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00003588 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003589 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3590
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003591 // Are we following APCS?
3592 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003593 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003594 return ABIArgInfo::getIgnore();
3595
Daniel Dunbareedf1512010-02-01 23:31:19 +00003596 // Complex types are all returned as packed integers.
3597 //
3598 // FIXME: Consider using 2 x vector types if the back end handles them
3599 // correctly.
3600 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003601 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003602 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003603
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003604 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003605 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003606 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003607 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003608 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003609 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003610 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003611 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3612 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003613 }
3614
3615 // Otherwise return in memory.
3616 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003617 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003618
3619 // Otherwise this is an AAPCS variant.
3620
Chris Lattner458b2aa2010-07-29 02:16:43 +00003621 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003622 return ABIArgInfo::getIgnore();
3623
Bob Wilson1d9269a2011-11-02 04:51:36 +00003624 // Check for homogeneous aggregates with AAPCS-VFP.
3625 if (getABIKind() == AAPCS_VFP) {
3626 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003627 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3628 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003629 // Homogeneous Aggregates are returned directly.
3630 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003631 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003632 }
3633
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003634 // Aggregates <= 4 bytes are returned in r0; other aggregates
3635 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003636 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003637 if (Size <= 32) {
3638 // Return in the smallest viable integer type.
3639 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003640 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003641 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003642 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3643 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003644 }
3645
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003646 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003647}
3648
Manman Renfef9e312012-10-16 19:18:39 +00003649/// isIllegalVector - check whether Ty is an illegal vector type.
3650bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3651 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3652 // Check whether VT is legal.
3653 unsigned NumElements = VT->getNumElements();
3654 uint64_t Size = getContext().getTypeSize(VT);
3655 // NumElements should be power of 2.
3656 if ((NumElements & (NumElements - 1)) != 0)
3657 return true;
3658 // Size should be greater than 32 bits.
3659 return Size <= 32;
3660 }
3661 return false;
3662}
3663
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003664llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003665 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003666 llvm::Type *BP = CGF.Int8PtrTy;
3667 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003668
3669 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003670 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003671 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003672
Tim Northover1711cc92013-06-21 23:05:33 +00003673 if (isEmptyRecord(getContext(), Ty, true)) {
3674 // These are ignored for parameter passing purposes.
3675 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3676 return Builder.CreateBitCast(Addr, PTy);
3677 }
3678
Manman Rencca54d02012-10-16 19:01:37 +00003679 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003680 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003681 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003682
3683 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3684 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003685 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3686 getABIKind() == ARMABIInfo::AAPCS)
3687 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3688 else
3689 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003690 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3691 if (isIllegalVectorType(Ty) && Size > 16) {
3692 IsIndirect = true;
3693 Size = 4;
3694 TyAlign = 4;
3695 }
Manman Rencca54d02012-10-16 19:01:37 +00003696
3697 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003698 if (TyAlign > 4) {
3699 assert((TyAlign & (TyAlign - 1)) == 0 &&
3700 "Alignment is not power of 2!");
3701 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3702 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3703 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003704 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003705 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003706
3707 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003708 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003709 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003710 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003711 "ap.next");
3712 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3713
Manman Renfef9e312012-10-16 19:18:39 +00003714 if (IsIndirect)
3715 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003716 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003717 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3718 // may not be correctly aligned for the vector type. We create an aligned
3719 // temporary space and copy the content over from ap.cur to the temporary
3720 // space. This is necessary if the natural alignment of the type is greater
3721 // than the ABI alignment.
3722 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3723 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3724 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3725 "var.align");
3726 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3727 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3728 Builder.CreateMemCpy(Dst, Src,
3729 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3730 TyAlign, false);
3731 Addr = AlignedTemp; //The content is in aligned location.
3732 }
3733 llvm::Type *PTy =
3734 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3735 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3736
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003737 return AddrTyped;
3738}
3739
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003740namespace {
3741
Derek Schuffa2020962012-10-16 22:30:41 +00003742class NaClARMABIInfo : public ABIInfo {
3743 public:
3744 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3745 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3746 virtual void computeInfo(CGFunctionInfo &FI) const;
3747 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3748 CodeGenFunction &CGF) const;
3749 private:
3750 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3751 ARMABIInfo NInfo; // Used for everything else.
3752};
3753
3754class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3755 public:
3756 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3757 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3758};
3759
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003760}
3761
Derek Schuffa2020962012-10-16 22:30:41 +00003762void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3763 if (FI.getASTCallingConvention() == CC_PnaclCall)
3764 PInfo.computeInfo(FI);
3765 else
3766 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3767}
3768
3769llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3770 CodeGenFunction &CGF) const {
3771 // Always use the native convention; calling pnacl-style varargs functions
3772 // is unsupported.
3773 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3774}
3775
Chris Lattner0cf24192010-06-28 20:05:43 +00003776//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003777// AArch64 ABI Implementation
3778//===----------------------------------------------------------------------===//
3779
3780namespace {
3781
3782class AArch64ABIInfo : public ABIInfo {
3783public:
3784 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3785
3786private:
3787 // The AArch64 PCS is explicit about return types and argument types being
3788 // handled identically, so we don't need to draw a distinction between
3789 // Argument and Return classification.
3790 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3791 int &FreeVFPRegs) const;
3792
3793 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3794 llvm::Type *DirectTy = 0) const;
3795
3796 virtual void computeInfo(CGFunctionInfo &FI) const;
3797
3798 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3799 CodeGenFunction &CGF) const;
3800};
3801
3802class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3803public:
3804 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3805 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3806
3807 const AArch64ABIInfo &getABIInfo() const {
3808 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3809 }
3810
3811 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3812 return 31;
3813 }
3814
3815 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3816 llvm::Value *Address) const {
3817 // 0-31 are x0-x30 and sp: 8 bytes each
3818 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3819 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3820
3821 // 64-95 are v0-v31: 16 bytes each
3822 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3823 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3824
3825 return false;
3826 }
3827
3828};
3829
3830}
3831
3832void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3833 int FreeIntRegs = 8, FreeVFPRegs = 8;
3834
3835 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3836 FreeIntRegs, FreeVFPRegs);
3837
3838 FreeIntRegs = FreeVFPRegs = 8;
3839 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3840 it != ie; ++it) {
3841 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3842
3843 }
3844}
3845
3846ABIArgInfo
3847AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3848 bool IsInt, llvm::Type *DirectTy) const {
3849 if (FreeRegs >= RegsNeeded) {
3850 FreeRegs -= RegsNeeded;
3851 return ABIArgInfo::getDirect(DirectTy);
3852 }
3853
3854 llvm::Type *Padding = 0;
3855
3856 // We need padding so that later arguments don't get filled in anyway. That
3857 // wouldn't happen if only ByVal arguments followed in the same category, but
3858 // a large structure will simply seem to be a pointer as far as LLVM is
3859 // concerned.
3860 if (FreeRegs > 0) {
3861 if (IsInt)
3862 Padding = llvm::Type::getInt64Ty(getVMContext());
3863 else
3864 Padding = llvm::Type::getFloatTy(getVMContext());
3865
3866 // Either [N x i64] or [N x float].
3867 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3868 FreeRegs = 0;
3869 }
3870
3871 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3872 /*IsByVal=*/ true, /*Realign=*/ false,
3873 Padding);
3874}
3875
3876
3877ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3878 int &FreeIntRegs,
3879 int &FreeVFPRegs) const {
3880 // Can only occurs for return, but harmless otherwise.
3881 if (Ty->isVoidType())
3882 return ABIArgInfo::getIgnore();
3883
3884 // Large vector types should be returned via memory. There's no such concept
3885 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3886 // classified they'd go into memory (see B.3).
3887 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3888 if (FreeIntRegs > 0)
3889 --FreeIntRegs;
3890 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3891 }
3892
3893 // All non-aggregate LLVM types have a concrete ABI representation so they can
3894 // be passed directly. After this block we're guaranteed to be in a
3895 // complicated case.
3896 if (!isAggregateTypeForABI(Ty)) {
3897 // Treat an enum type as its underlying type.
3898 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3899 Ty = EnumTy->getDecl()->getIntegerType();
3900
3901 if (Ty->isFloatingType() || Ty->isVectorType())
3902 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3903
3904 assert(getContext().getTypeSize(Ty) <= 128 &&
3905 "unexpectedly large scalar type");
3906
3907 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3908
3909 // If the type may need padding registers to ensure "alignment", we must be
3910 // careful when this is accounted for. Increasing the effective size covers
3911 // all cases.
3912 if (getContext().getTypeAlign(Ty) == 128)
3913 RegsNeeded += FreeIntRegs % 2 != 0;
3914
3915 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3916 }
3917
Mark Lacey3825e832013-10-06 01:33:34 +00003918 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003919 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00003920 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003921 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00003922 }
3923
3924 if (isEmptyRecord(getContext(), Ty, true)) {
3925 if (!getContext().getLangOpts().CPlusPlus) {
3926 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3927 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3928 // the object for parameter-passsing purposes.
3929 return ABIArgInfo::getIgnore();
3930 }
3931
3932 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3933 // description of va_arg in the PCS require that an empty struct does
3934 // actually occupy space for parameter-passing. I'm hoping for a
3935 // clarification giving an explicit paragraph to point to in future.
3936 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3937 llvm::Type::getInt8Ty(getVMContext()));
3938 }
3939
3940 // Homogeneous vector aggregates get passed in registers or on the stack.
3941 const Type *Base = 0;
3942 uint64_t NumMembers = 0;
3943 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3944 assert(Base && "Base class should be set for homogeneous aggregate");
3945 // Homogeneous aggregates are passed and returned directly.
3946 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3947 /*IsInt=*/ false);
3948 }
3949
3950 uint64_t Size = getContext().getTypeSize(Ty);
3951 if (Size <= 128) {
3952 // Small structs can use the same direct type whether they're in registers
3953 // or on the stack.
3954 llvm::Type *BaseTy;
3955 unsigned NumBases;
3956 int SizeInRegs = (Size + 63) / 64;
3957
3958 if (getContext().getTypeAlign(Ty) == 128) {
3959 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3960 NumBases = 1;
3961
3962 // If the type may need padding registers to ensure "alignment", we must
3963 // be careful when this is accounted for. Increasing the effective size
3964 // covers all cases.
3965 SizeInRegs += FreeIntRegs % 2 != 0;
3966 } else {
3967 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3968 NumBases = SizeInRegs;
3969 }
3970 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3971
3972 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3973 /*IsInt=*/ true, DirectTy);
3974 }
3975
3976 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3977 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3978 --FreeIntRegs;
3979 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3980}
3981
3982llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3983 CodeGenFunction &CGF) const {
3984 // The AArch64 va_list type and handling is specified in the Procedure Call
3985 // Standard, section B.4:
3986 //
3987 // struct {
3988 // void *__stack;
3989 // void *__gr_top;
3990 // void *__vr_top;
3991 // int __gr_offs;
3992 // int __vr_offs;
3993 // };
3994
3995 assert(!CGF.CGM.getDataLayout().isBigEndian()
3996 && "va_arg not implemented for big-endian AArch64");
3997
3998 int FreeIntRegs = 8, FreeVFPRegs = 8;
3999 Ty = CGF.getContext().getCanonicalType(Ty);
4000 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4001
4002 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4003 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4004 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4005 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4006
4007 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4008 int reg_top_index;
4009 int RegSize;
4010 if (FreeIntRegs < 8) {
4011 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4012 // 3 is the field number of __gr_offs
4013 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4014 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4015 reg_top_index = 1; // field number for __gr_top
4016 RegSize = 8 * (8 - FreeIntRegs);
4017 } else {
4018 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4019 // 4 is the field number of __vr_offs.
4020 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4021 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4022 reg_top_index = 2; // field number for __vr_top
4023 RegSize = 16 * (8 - FreeVFPRegs);
4024 }
4025
4026 //=======================================
4027 // Find out where argument was passed
4028 //=======================================
4029
4030 // If reg_offs >= 0 we're already using the stack for this type of
4031 // argument. We don't want to keep updating reg_offs (in case it overflows,
4032 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4033 // whatever they get).
4034 llvm::Value *UsingStack = 0;
4035 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4036 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4037
4038 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4039
4040 // Otherwise, at least some kind of argument could go in these registers, the
4041 // quesiton is whether this particular type is too big.
4042 CGF.EmitBlock(MaybeRegBlock);
4043
4044 // Integer arguments may need to correct register alignment (for example a
4045 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4046 // align __gr_offs to calculate the potential address.
4047 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4048 int Align = getContext().getTypeAlign(Ty) / 8;
4049
4050 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4051 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4052 "align_regoffs");
4053 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4054 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4055 "aligned_regoffs");
4056 }
4057
4058 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4059 llvm::Value *NewOffset = 0;
4060 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4061 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4062 "new_reg_offs");
4063 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4064
4065 // Now we're in a position to decide whether this argument really was in
4066 // registers or not.
4067 llvm::Value *InRegs = 0;
4068 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4069 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4070 "inreg");
4071
4072 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4073
4074 //=======================================
4075 // Argument was in registers
4076 //=======================================
4077
4078 // Now we emit the code for if the argument was originally passed in
4079 // registers. First start the appropriate block:
4080 CGF.EmitBlock(InRegBlock);
4081
4082 llvm::Value *reg_top_p = 0, *reg_top = 0;
4083 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4084 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4085 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4086 llvm::Value *RegAddr = 0;
4087 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4088
4089 if (!AI.isDirect()) {
4090 // If it's been passed indirectly (actually a struct), whatever we find from
4091 // stored registers or on the stack will actually be a struct **.
4092 MemTy = llvm::PointerType::getUnqual(MemTy);
4093 }
4094
4095 const Type *Base = 0;
4096 uint64_t NumMembers;
4097 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4098 && NumMembers > 1) {
4099 // Homogeneous aggregates passed in registers will have their elements split
4100 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4101 // qN+1, ...). We reload and store into a temporary local variable
4102 // contiguously.
4103 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4104 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4105 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4106 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4107
4108 for (unsigned i = 0; i < NumMembers; ++i) {
4109 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4110 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4111 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4112 llvm::PointerType::getUnqual(BaseTy));
4113 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4114
4115 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4116 CGF.Builder.CreateStore(Elem, StoreAddr);
4117 }
4118
4119 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4120 } else {
4121 // Otherwise the object is contiguous in memory
4122 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4123 }
4124
4125 CGF.EmitBranch(ContBlock);
4126
4127 //=======================================
4128 // Argument was on the stack
4129 //=======================================
4130 CGF.EmitBlock(OnStackBlock);
4131
4132 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4133 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4134 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4135
4136 // Again, stack arguments may need realigmnent. In this case both integer and
4137 // floating-point ones might be affected.
4138 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4139 int Align = getContext().getTypeAlign(Ty) / 8;
4140
4141 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4142
4143 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4144 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4145 "align_stack");
4146 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4147 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4148 "align_stack");
4149
4150 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4151 }
4152
4153 uint64_t StackSize;
4154 if (AI.isDirect())
4155 StackSize = getContext().getTypeSize(Ty) / 8;
4156 else
4157 StackSize = 8;
4158
4159 // All stack slots are 8 bytes
4160 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4161
4162 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4163 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4164 "new_stack");
4165
4166 // Write the new value of __stack for the next call to va_arg
4167 CGF.Builder.CreateStore(NewStack, stack_p);
4168
4169 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4170
4171 CGF.EmitBranch(ContBlock);
4172
4173 //=======================================
4174 // Tidy up
4175 //=======================================
4176 CGF.EmitBlock(ContBlock);
4177
4178 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4179 ResAddr->addIncoming(RegAddr, InRegBlock);
4180 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4181
4182 if (AI.isDirect())
4183 return ResAddr;
4184
4185 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4186}
4187
4188//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004189// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004190//===----------------------------------------------------------------------===//
4191
4192namespace {
4193
Justin Holewinski83e96682012-05-24 17:43:12 +00004194class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004195public:
Justin Holewinski36837432013-03-30 14:38:24 +00004196 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004197
4198 ABIArgInfo classifyReturnType(QualType RetTy) const;
4199 ABIArgInfo classifyArgumentType(QualType Ty) const;
4200
4201 virtual void computeInfo(CGFunctionInfo &FI) const;
4202 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4203 CodeGenFunction &CFG) const;
4204};
4205
Justin Holewinski83e96682012-05-24 17:43:12 +00004206class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004207public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004208 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4209 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski38031972011-10-05 17:58:44 +00004210
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004211 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4212 CodeGen::CodeGenModule &M) const;
Justin Holewinski36837432013-03-30 14:38:24 +00004213private:
4214 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004215};
4216
Justin Holewinski83e96682012-05-24 17:43:12 +00004217ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004218 if (RetTy->isVoidType())
4219 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004220
4221 // note: this is different from default ABI
4222 if (!RetTy->isScalarType())
4223 return ABIArgInfo::getDirect();
4224
4225 // Treat an enum type as its underlying type.
4226 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4227 RetTy = EnumTy->getDecl()->getIntegerType();
4228
4229 return (RetTy->isPromotableIntegerType() ?
4230 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004231}
4232
Justin Holewinski83e96682012-05-24 17:43:12 +00004233ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004234 // Treat an enum type as its underlying type.
4235 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4236 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004237
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004238 return (Ty->isPromotableIntegerType() ?
4239 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004240}
4241
Justin Holewinski83e96682012-05-24 17:43:12 +00004242void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004243 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4244 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4245 it != ie; ++it)
4246 it->info = classifyArgumentType(it->type);
4247
4248 // Always honor user-specified calling convention.
4249 if (FI.getCallingConvention() != llvm::CallingConv::C)
4250 return;
4251
John McCall882987f2013-02-28 19:01:20 +00004252 FI.setEffectiveCallingConvention(getRuntimeCC());
4253}
4254
Justin Holewinski83e96682012-05-24 17:43:12 +00004255llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4256 CodeGenFunction &CFG) const {
4257 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004258}
4259
Justin Holewinski83e96682012-05-24 17:43:12 +00004260void NVPTXTargetCodeGenInfo::
4261SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4262 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004263 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4264 if (!FD) return;
4265
4266 llvm::Function *F = cast<llvm::Function>(GV);
4267
4268 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004269 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004270 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004271 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004272 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004273 // OpenCL __kernel functions get kernel metadata
4274 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004275 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004276 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004277 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004278 }
Justin Holewinski38031972011-10-05 17:58:44 +00004279
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004280 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004281 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004282 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004283 // __global__ functions cannot be called from the device, we do not
4284 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004285 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004286 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004287 }
4288}
4289
Justin Holewinski36837432013-03-30 14:38:24 +00004290void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4291 llvm::Module *M = F->getParent();
4292 llvm::LLVMContext &Ctx = M->getContext();
4293
4294 // Get "nvvm.annotations" metadata node
4295 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4296
4297 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4298 llvm::SmallVector<llvm::Value *, 3> MDVals;
4299 MDVals.push_back(F);
4300 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4301 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4302
4303 // Append metadata to nvvm.annotations
4304 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4305}
4306
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004307}
4308
4309//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004310// SystemZ ABI Implementation
4311//===----------------------------------------------------------------------===//
4312
4313namespace {
4314
4315class SystemZABIInfo : public ABIInfo {
4316public:
4317 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4318
4319 bool isPromotableIntegerType(QualType Ty) const;
4320 bool isCompoundType(QualType Ty) const;
4321 bool isFPArgumentType(QualType Ty) const;
4322
4323 ABIArgInfo classifyReturnType(QualType RetTy) const;
4324 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4325
4326 virtual void computeInfo(CGFunctionInfo &FI) const {
4327 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4328 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4329 it != ie; ++it)
4330 it->info = classifyArgumentType(it->type);
4331 }
4332
4333 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4334 CodeGenFunction &CGF) const;
4335};
4336
4337class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4338public:
4339 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4340 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4341};
4342
4343}
4344
4345bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4346 // Treat an enum type as its underlying type.
4347 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4348 Ty = EnumTy->getDecl()->getIntegerType();
4349
4350 // Promotable integer types are required to be promoted by the ABI.
4351 if (Ty->isPromotableIntegerType())
4352 return true;
4353
4354 // 32-bit values must also be promoted.
4355 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4356 switch (BT->getKind()) {
4357 case BuiltinType::Int:
4358 case BuiltinType::UInt:
4359 return true;
4360 default:
4361 return false;
4362 }
4363 return false;
4364}
4365
4366bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4367 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4368}
4369
4370bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4371 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4372 switch (BT->getKind()) {
4373 case BuiltinType::Float:
4374 case BuiltinType::Double:
4375 return true;
4376 default:
4377 return false;
4378 }
4379
4380 if (const RecordType *RT = Ty->getAsStructureType()) {
4381 const RecordDecl *RD = RT->getDecl();
4382 bool Found = false;
4383
4384 // If this is a C++ record, check the bases first.
4385 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4386 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4387 E = CXXRD->bases_end(); I != E; ++I) {
4388 QualType Base = I->getType();
4389
4390 // Empty bases don't affect things either way.
4391 if (isEmptyRecord(getContext(), Base, true))
4392 continue;
4393
4394 if (Found)
4395 return false;
4396 Found = isFPArgumentType(Base);
4397 if (!Found)
4398 return false;
4399 }
4400
4401 // Check the fields.
4402 for (RecordDecl::field_iterator I = RD->field_begin(),
4403 E = RD->field_end(); I != E; ++I) {
4404 const FieldDecl *FD = *I;
4405
4406 // Empty bitfields don't affect things either way.
4407 // Unlike isSingleElementStruct(), empty structure and array fields
4408 // do count. So do anonymous bitfields that aren't zero-sized.
4409 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4410 return true;
4411
4412 // Unlike isSingleElementStruct(), arrays do not count.
4413 // Nested isFPArgumentType structures still do though.
4414 if (Found)
4415 return false;
4416 Found = isFPArgumentType(FD->getType());
4417 if (!Found)
4418 return false;
4419 }
4420
4421 // Unlike isSingleElementStruct(), trailing padding is allowed.
4422 // An 8-byte aligned struct s { float f; } is passed as a double.
4423 return Found;
4424 }
4425
4426 return false;
4427}
4428
4429llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4430 CodeGenFunction &CGF) const {
4431 // Assume that va_list type is correct; should be pointer to LLVM type:
4432 // struct {
4433 // i64 __gpr;
4434 // i64 __fpr;
4435 // i8 *__overflow_arg_area;
4436 // i8 *__reg_save_area;
4437 // };
4438
4439 // Every argument occupies 8 bytes and is passed by preference in either
4440 // GPRs or FPRs.
4441 Ty = CGF.getContext().getCanonicalType(Ty);
4442 ABIArgInfo AI = classifyArgumentType(Ty);
4443 bool InFPRs = isFPArgumentType(Ty);
4444
4445 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4446 bool IsIndirect = AI.isIndirect();
4447 unsigned UnpaddedBitSize;
4448 if (IsIndirect) {
4449 APTy = llvm::PointerType::getUnqual(APTy);
4450 UnpaddedBitSize = 64;
4451 } else
4452 UnpaddedBitSize = getContext().getTypeSize(Ty);
4453 unsigned PaddedBitSize = 64;
4454 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4455
4456 unsigned PaddedSize = PaddedBitSize / 8;
4457 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4458
4459 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4460 if (InFPRs) {
4461 MaxRegs = 4; // Maximum of 4 FPR arguments
4462 RegCountField = 1; // __fpr
4463 RegSaveIndex = 16; // save offset for f0
4464 RegPadding = 0; // floats are passed in the high bits of an FPR
4465 } else {
4466 MaxRegs = 5; // Maximum of 5 GPR arguments
4467 RegCountField = 0; // __gpr
4468 RegSaveIndex = 2; // save offset for r2
4469 RegPadding = Padding; // values are passed in the low bits of a GPR
4470 }
4471
4472 llvm::Value *RegCountPtr =
4473 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4474 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4475 llvm::Type *IndexTy = RegCount->getType();
4476 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4477 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4478 "fits_in_regs");
4479
4480 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4481 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4482 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4483 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4484
4485 // Emit code to load the value if it was passed in registers.
4486 CGF.EmitBlock(InRegBlock);
4487
4488 // Work out the address of an argument register.
4489 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4490 llvm::Value *ScaledRegCount =
4491 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4492 llvm::Value *RegBase =
4493 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4494 llvm::Value *RegOffset =
4495 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4496 llvm::Value *RegSaveAreaPtr =
4497 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4498 llvm::Value *RegSaveArea =
4499 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4500 llvm::Value *RawRegAddr =
4501 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4502 llvm::Value *RegAddr =
4503 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4504
4505 // Update the register count
4506 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4507 llvm::Value *NewRegCount =
4508 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4509 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4510 CGF.EmitBranch(ContBlock);
4511
4512 // Emit code to load the value if it was passed in memory.
4513 CGF.EmitBlock(InMemBlock);
4514
4515 // Work out the address of a stack argument.
4516 llvm::Value *OverflowArgAreaPtr =
4517 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4518 llvm::Value *OverflowArgArea =
4519 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4520 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4521 llvm::Value *RawMemAddr =
4522 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4523 llvm::Value *MemAddr =
4524 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4525
4526 // Update overflow_arg_area_ptr pointer
4527 llvm::Value *NewOverflowArgArea =
4528 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4529 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4530 CGF.EmitBranch(ContBlock);
4531
4532 // Return the appropriate result.
4533 CGF.EmitBlock(ContBlock);
4534 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4535 ResAddr->addIncoming(RegAddr, InRegBlock);
4536 ResAddr->addIncoming(MemAddr, InMemBlock);
4537
4538 if (IsIndirect)
4539 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4540
4541 return ResAddr;
4542}
4543
John McCall1fe2a8c2013-06-18 02:46:29 +00004544bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4545 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4546 assert(Triple.getArch() == llvm::Triple::x86);
4547
4548 switch (Opts.getStructReturnConvention()) {
4549 case CodeGenOptions::SRCK_Default:
4550 break;
4551 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4552 return false;
4553 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4554 return true;
4555 }
4556
4557 if (Triple.isOSDarwin())
4558 return true;
4559
4560 switch (Triple.getOS()) {
4561 case llvm::Triple::Cygwin:
4562 case llvm::Triple::MinGW32:
4563 case llvm::Triple::AuroraUX:
4564 case llvm::Triple::DragonFly:
4565 case llvm::Triple::FreeBSD:
4566 case llvm::Triple::OpenBSD:
4567 case llvm::Triple::Bitrig:
4568 case llvm::Triple::Win32:
4569 return true;
4570 default:
4571 return false;
4572 }
4573}
Ulrich Weigand47445072013-05-06 16:26:41 +00004574
4575ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4576 if (RetTy->isVoidType())
4577 return ABIArgInfo::getIgnore();
4578 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4579 return ABIArgInfo::getIndirect(0);
4580 return (isPromotableIntegerType(RetTy) ?
4581 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4582}
4583
4584ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4585 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004586 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004587 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4588
4589 // Integers and enums are extended to full register width.
4590 if (isPromotableIntegerType(Ty))
4591 return ABIArgInfo::getExtend();
4592
4593 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4594 uint64_t Size = getContext().getTypeSize(Ty);
4595 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004596 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004597
4598 // Handle small structures.
4599 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4600 // Structures with flexible arrays have variable length, so really
4601 // fail the size test above.
4602 const RecordDecl *RD = RT->getDecl();
4603 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004604 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004605
4606 // The structure is passed as an unextended integer, a float, or a double.
4607 llvm::Type *PassTy;
4608 if (isFPArgumentType(Ty)) {
4609 assert(Size == 32 || Size == 64);
4610 if (Size == 32)
4611 PassTy = llvm::Type::getFloatTy(getVMContext());
4612 else
4613 PassTy = llvm::Type::getDoubleTy(getVMContext());
4614 } else
4615 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4616 return ABIArgInfo::getDirect(PassTy);
4617 }
4618
4619 // Non-structure compounds are passed indirectly.
4620 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004621 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004622
4623 return ABIArgInfo::getDirect(0);
4624}
4625
4626//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004627// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004628//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004629
4630namespace {
4631
4632class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4633public:
Chris Lattner2b037972010-07-29 02:01:43 +00004634 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4635 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004636 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4637 CodeGen::CodeGenModule &M) const;
4638};
4639
4640}
4641
4642void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4643 llvm::GlobalValue *GV,
4644 CodeGen::CodeGenModule &M) const {
4645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4646 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4647 // Handle 'interrupt' attribute:
4648 llvm::Function *F = cast<llvm::Function>(GV);
4649
4650 // Step 1: Set ISR calling convention.
4651 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4652
4653 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004654 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004655
4656 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004657 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004658 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004659 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004660 GV, &M.getModule());
4661 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004662 }
4663}
4664
Chris Lattner0cf24192010-06-28 20:05:43 +00004665//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004666// MIPS ABI Implementation. This works for both little-endian and
4667// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004668//===----------------------------------------------------------------------===//
4669
John McCall943fae92010-05-27 06:19:26 +00004670namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004671class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004672 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004673 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4674 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004675 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004676 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004677 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004678 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004679public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004680 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004681 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004682 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004683
4684 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004685 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004686 virtual void computeInfo(CGFunctionInfo &FI) const;
4687 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4688 CodeGenFunction &CGF) const;
4689};
4690
John McCall943fae92010-05-27 06:19:26 +00004691class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004692 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004693public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004694 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4695 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004696 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004697
4698 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4699 return 29;
4700 }
4701
Reed Kotler373feca2013-01-16 17:10:28 +00004702 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4703 CodeGen::CodeGenModule &CGM) const {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004704 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4705 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004706 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004707 if (FD->hasAttr<Mips16Attr>()) {
4708 Fn->addFnAttr("mips16");
4709 }
4710 else if (FD->hasAttr<NoMips16Attr>()) {
4711 Fn->addFnAttr("nomips16");
4712 }
Reed Kotler373feca2013-01-16 17:10:28 +00004713 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004714
John McCall943fae92010-05-27 06:19:26 +00004715 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004716 llvm::Value *Address) const;
John McCall3480ef22011-08-30 01:42:09 +00004717
4718 unsigned getSizeOfUnwindException() const {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004719 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004720 }
John McCall943fae92010-05-27 06:19:26 +00004721};
4722}
4723
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004724void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004725 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004726 llvm::IntegerType *IntTy =
4727 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004728
4729 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4730 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4731 ArgList.push_back(IntTy);
4732
4733 // If necessary, add one more integer type to ArgList.
4734 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4735
4736 if (R)
4737 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004738}
4739
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004740// In N32/64, an aligned double precision floating point field is passed in
4741// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004742llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004743 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4744
4745 if (IsO32) {
4746 CoerceToIntArgs(TySize, ArgList);
4747 return llvm::StructType::get(getVMContext(), ArgList);
4748 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004749
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004750 if (Ty->isComplexType())
4751 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004752
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004753 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004754
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004755 // Unions/vectors are passed in integer registers.
4756 if (!RT || !RT->isStructureOrClassType()) {
4757 CoerceToIntArgs(TySize, ArgList);
4758 return llvm::StructType::get(getVMContext(), ArgList);
4759 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004760
4761 const RecordDecl *RD = RT->getDecl();
4762 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004763 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004764
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004765 uint64_t LastOffset = 0;
4766 unsigned idx = 0;
4767 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4768
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004769 // Iterate over fields in the struct/class and check if there are any aligned
4770 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004771 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4772 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004773 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004774 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4775
4776 if (!BT || BT->getKind() != BuiltinType::Double)
4777 continue;
4778
4779 uint64_t Offset = Layout.getFieldOffset(idx);
4780 if (Offset % 64) // Ignore doubles that are not aligned.
4781 continue;
4782
4783 // Add ((Offset - LastOffset) / 64) args of type i64.
4784 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4785 ArgList.push_back(I64);
4786
4787 // Add double type.
4788 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4789 LastOffset = Offset + 64;
4790 }
4791
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004792 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4793 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004794
4795 return llvm::StructType::get(getVMContext(), ArgList);
4796}
4797
Akira Hatanakaddd66342013-10-29 18:41:15 +00004798llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4799 uint64_t Offset) const {
4800 if (OrigOffset + MinABIStackAlignInBytes > Offset)
4801 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004802
Akira Hatanakaddd66342013-10-29 18:41:15 +00004803 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004804}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00004805
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004806ABIArgInfo
4807MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00004808 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004809 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004810 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004811
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004812 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4813 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00004814 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4815 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004816
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004817 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004818 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004819 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004820 return ABIArgInfo::getIgnore();
4821
Mark Lacey3825e832013-10-06 01:33:34 +00004822 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004823 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004824 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004825 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00004826
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004827 // If we have reached here, aggregates are passed directly by coercing to
4828 // another structure type. Padding is inserted if the offset of the
4829 // aggregate is unaligned.
4830 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00004831 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004832 }
4833
4834 // Treat an enum type as its underlying type.
4835 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4836 Ty = EnumTy->getDecl()->getIntegerType();
4837
Akira Hatanaka1632af62012-01-09 19:31:25 +00004838 if (Ty->isPromotableIntegerType())
4839 return ABIArgInfo::getExtend();
4840
Akira Hatanakaddd66342013-10-29 18:41:15 +00004841 return ABIArgInfo::getDirect(
4842 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004843}
4844
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004845llvm::Type*
4846MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00004847 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004848 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004849
Akira Hatanakab6f74432012-02-09 18:49:26 +00004850 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004851 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00004852 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4853 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004854
Akira Hatanakab6f74432012-02-09 18:49:26 +00004855 // N32/64 returns struct/classes in floating point registers if the
4856 // following conditions are met:
4857 // 1. The size of the struct/class is no larger than 128-bit.
4858 // 2. The struct/class has one or two fields all of which are floating
4859 // point types.
4860 // 3. The offset of the first field is zero (this follows what gcc does).
4861 //
4862 // Any other composite results are returned in integer registers.
4863 //
4864 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4865 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4866 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004867 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004868
Akira Hatanakab6f74432012-02-09 18:49:26 +00004869 if (!BT || !BT->isFloatingPoint())
4870 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004871
David Blaikie2d7c57e2012-04-30 02:36:29 +00004872 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00004873 }
4874
4875 if (b == e)
4876 return llvm::StructType::get(getVMContext(), RTList,
4877 RD->hasAttr<PackedAttr>());
4878
4879 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004880 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004881 }
4882
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004883 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004884 return llvm::StructType::get(getVMContext(), RTList);
4885}
4886
Akira Hatanakab579fe52011-06-02 00:09:17 +00004887ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00004888 uint64_t Size = getContext().getTypeSize(RetTy);
4889
4890 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004891 return ABIArgInfo::getIgnore();
4892
Akira Hatanakac37eddf2012-05-11 21:01:17 +00004893 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00004894 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004895 return ABIArgInfo::getIndirect(0);
4896
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004897 if (Size <= 128) {
4898 if (RetTy->isAnyComplexType())
4899 return ABIArgInfo::getDirect();
4900
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004901 // O32 returns integer vectors in registers.
4902 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4903 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4904
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004905 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004906 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4907 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00004908
4909 return ABIArgInfo::getIndirect(0);
4910 }
4911
4912 // Treat an enum type as its underlying type.
4913 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4914 RetTy = EnumTy->getDecl()->getIntegerType();
4915
4916 return (RetTy->isPromotableIntegerType() ?
4917 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4918}
4919
4920void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00004921 ABIArgInfo &RetInfo = FI.getReturnInfo();
4922 RetInfo = classifyReturnType(FI.getReturnType());
4923
4924 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004925 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00004926
Akira Hatanakab579fe52011-06-02 00:09:17 +00004927 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4928 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004929 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00004930}
4931
4932llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4933 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004934 llvm::Type *BP = CGF.Int8PtrTy;
4935 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004936
4937 CGBuilderTy &Builder = CGF.Builder;
4938 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4939 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00004940 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004941 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4942 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00004943 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00004944 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004945
4946 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00004947 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4948 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4949 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4950 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004951 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4952 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4953 }
4954 else
4955 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4956
4957 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00004958 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004959 uint64_t Offset =
4960 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4961 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00004962 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004963 "ap.next");
4964 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4965
4966 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004967}
4968
John McCall943fae92010-05-27 06:19:26 +00004969bool
4970MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4971 llvm::Value *Address) const {
4972 // This information comes from gcc's implementation, which seems to
4973 // as canonical as it gets.
4974
John McCall943fae92010-05-27 06:19:26 +00004975 // Everything on MIPS is 4 bytes. Double-precision FP registers
4976 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004977 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00004978
4979 // 0-31 are the general purpose registers, $0 - $31.
4980 // 32-63 are the floating-point registers, $f0 - $f31.
4981 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4982 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00004983 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00004984
4985 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4986 // They are one bit wide and ignored here.
4987
4988 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4989 // (coprocessor 1 is the FP unit)
4990 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4991 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4992 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004993 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00004994 return false;
4995}
4996
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004997//===----------------------------------------------------------------------===//
4998// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4999// Currently subclassed only to implement custom OpenCL C function attribute
5000// handling.
5001//===----------------------------------------------------------------------===//
5002
5003namespace {
5004
5005class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5006public:
5007 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5008 : DefaultTargetCodeGenInfo(CGT) {}
5009
5010 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5011 CodeGen::CodeGenModule &M) const;
5012};
5013
5014void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5015 llvm::GlobalValue *GV,
5016 CodeGen::CodeGenModule &M) const {
5017 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5018 if (!FD) return;
5019
5020 llvm::Function *F = cast<llvm::Function>(GV);
5021
David Blaikiebbafb8a2012-03-11 07:00:24 +00005022 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005023 if (FD->hasAttr<OpenCLKernelAttr>()) {
5024 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005025 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005026 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5027 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005028 // Convert the reqd_work_group_size() attributes to metadata.
5029 llvm::LLVMContext &Context = F->getContext();
5030 llvm::NamedMDNode *OpenCLMetadata =
5031 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5032
5033 SmallVector<llvm::Value*, 5> Operands;
5034 Operands.push_back(F);
5035
Chris Lattnerece04092012-02-07 00:39:47 +00005036 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005037 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005038 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005039 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005040 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005041 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005042
5043 // Add a boolean constant operand for "required" (true) or "hint" (false)
5044 // for implementing the work_group_size_hint attr later. Currently
5045 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005046 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005047 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5048 }
5049 }
5050 }
5051}
5052
5053}
John McCall943fae92010-05-27 06:19:26 +00005054
Tony Linthicum76329bf2011-12-12 21:14:55 +00005055//===----------------------------------------------------------------------===//
5056// Hexagon ABI Implementation
5057//===----------------------------------------------------------------------===//
5058
5059namespace {
5060
5061class HexagonABIInfo : public ABIInfo {
5062
5063
5064public:
5065 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5066
5067private:
5068
5069 ABIArgInfo classifyReturnType(QualType RetTy) const;
5070 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5071
5072 virtual void computeInfo(CGFunctionInfo &FI) const;
5073
5074 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5075 CodeGenFunction &CGF) const;
5076};
5077
5078class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5079public:
5080 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5081 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5082
5083 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5084 return 29;
5085 }
5086};
5087
5088}
5089
5090void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5091 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5092 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5093 it != ie; ++it)
5094 it->info = classifyArgumentType(it->type);
5095}
5096
5097ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5098 if (!isAggregateTypeForABI(Ty)) {
5099 // Treat an enum type as its underlying type.
5100 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5101 Ty = EnumTy->getDecl()->getIntegerType();
5102
5103 return (Ty->isPromotableIntegerType() ?
5104 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5105 }
5106
5107 // Ignore empty records.
5108 if (isEmptyRecord(getContext(), Ty, true))
5109 return ABIArgInfo::getIgnore();
5110
Mark Lacey3825e832013-10-06 01:33:34 +00005111 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005112 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005113
5114 uint64_t Size = getContext().getTypeSize(Ty);
5115 if (Size > 64)
5116 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5117 // Pass in the smallest viable integer type.
5118 else if (Size > 32)
5119 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5120 else if (Size > 16)
5121 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5122 else if (Size > 8)
5123 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5124 else
5125 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5126}
5127
5128ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5129 if (RetTy->isVoidType())
5130 return ABIArgInfo::getIgnore();
5131
5132 // Large vector types should be returned via memory.
5133 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5134 return ABIArgInfo::getIndirect(0);
5135
5136 if (!isAggregateTypeForABI(RetTy)) {
5137 // Treat an enum type as its underlying type.
5138 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5139 RetTy = EnumTy->getDecl()->getIntegerType();
5140
5141 return (RetTy->isPromotableIntegerType() ?
5142 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5143 }
5144
5145 // Structures with either a non-trivial destructor or a non-trivial
5146 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005147 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005148 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5149
5150 if (isEmptyRecord(getContext(), RetTy, true))
5151 return ABIArgInfo::getIgnore();
5152
5153 // Aggregates <= 8 bytes are returned in r0; other aggregates
5154 // are returned indirectly.
5155 uint64_t Size = getContext().getTypeSize(RetTy);
5156 if (Size <= 64) {
5157 // Return in the smallest viable integer type.
5158 if (Size <= 8)
5159 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5160 if (Size <= 16)
5161 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5162 if (Size <= 32)
5163 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5164 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5165 }
5166
5167 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5168}
5169
5170llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005171 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005172 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005173 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005174
5175 CGBuilderTy &Builder = CGF.Builder;
5176 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5177 "ap");
5178 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5179 llvm::Type *PTy =
5180 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5181 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5182
5183 uint64_t Offset =
5184 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5185 llvm::Value *NextAddr =
5186 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5187 "ap.next");
5188 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5189
5190 return AddrTyped;
5191}
5192
5193
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005194//===----------------------------------------------------------------------===//
5195// SPARC v9 ABI Implementation.
5196// Based on the SPARC Compliance Definition version 2.4.1.
5197//
5198// Function arguments a mapped to a nominal "parameter array" and promoted to
5199// registers depending on their type. Each argument occupies 8 or 16 bytes in
5200// the array, structs larger than 16 bytes are passed indirectly.
5201//
5202// One case requires special care:
5203//
5204// struct mixed {
5205// int i;
5206// float f;
5207// };
5208//
5209// When a struct mixed is passed by value, it only occupies 8 bytes in the
5210// parameter array, but the int is passed in an integer register, and the float
5211// is passed in a floating point register. This is represented as two arguments
5212// with the LLVM IR inreg attribute:
5213//
5214// declare void f(i32 inreg %i, float inreg %f)
5215//
5216// The code generator will only allocate 4 bytes from the parameter array for
5217// the inreg arguments. All other arguments are allocated a multiple of 8
5218// bytes.
5219//
5220namespace {
5221class SparcV9ABIInfo : public ABIInfo {
5222public:
5223 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5224
5225private:
5226 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5227 virtual void computeInfo(CGFunctionInfo &FI) const;
5228 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5229 CodeGenFunction &CGF) const;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005230
5231 // Coercion type builder for structs passed in registers. The coercion type
5232 // serves two purposes:
5233 //
5234 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5235 // in registers.
5236 // 2. Expose aligned floating point elements as first-level elements, so the
5237 // code generator knows to pass them in floating point registers.
5238 //
5239 // We also compute the InReg flag which indicates that the struct contains
5240 // aligned 32-bit floats.
5241 //
5242 struct CoerceBuilder {
5243 llvm::LLVMContext &Context;
5244 const llvm::DataLayout &DL;
5245 SmallVector<llvm::Type*, 8> Elems;
5246 uint64_t Size;
5247 bool InReg;
5248
5249 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5250 : Context(c), DL(dl), Size(0), InReg(false) {}
5251
5252 // Pad Elems with integers until Size is ToSize.
5253 void pad(uint64_t ToSize) {
5254 assert(ToSize >= Size && "Cannot remove elements");
5255 if (ToSize == Size)
5256 return;
5257
5258 // Finish the current 64-bit word.
5259 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5260 if (Aligned > Size && Aligned <= ToSize) {
5261 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5262 Size = Aligned;
5263 }
5264
5265 // Add whole 64-bit words.
5266 while (Size + 64 <= ToSize) {
5267 Elems.push_back(llvm::Type::getInt64Ty(Context));
5268 Size += 64;
5269 }
5270
5271 // Final in-word padding.
5272 if (Size < ToSize) {
5273 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5274 Size = ToSize;
5275 }
5276 }
5277
5278 // Add a floating point element at Offset.
5279 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5280 // Unaligned floats are treated as integers.
5281 if (Offset % Bits)
5282 return;
5283 // The InReg flag is only required if there are any floats < 64 bits.
5284 if (Bits < 64)
5285 InReg = true;
5286 pad(Offset);
5287 Elems.push_back(Ty);
5288 Size = Offset + Bits;
5289 }
5290
5291 // Add a struct type to the coercion type, starting at Offset (in bits).
5292 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5293 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5294 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5295 llvm::Type *ElemTy = StrTy->getElementType(i);
5296 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5297 switch (ElemTy->getTypeID()) {
5298 case llvm::Type::StructTyID:
5299 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5300 break;
5301 case llvm::Type::FloatTyID:
5302 addFloat(ElemOffset, ElemTy, 32);
5303 break;
5304 case llvm::Type::DoubleTyID:
5305 addFloat(ElemOffset, ElemTy, 64);
5306 break;
5307 case llvm::Type::FP128TyID:
5308 addFloat(ElemOffset, ElemTy, 128);
5309 break;
5310 case llvm::Type::PointerTyID:
5311 if (ElemOffset % 64 == 0) {
5312 pad(ElemOffset);
5313 Elems.push_back(ElemTy);
5314 Size += 64;
5315 }
5316 break;
5317 default:
5318 break;
5319 }
5320 }
5321 }
5322
5323 // Check if Ty is a usable substitute for the coercion type.
5324 bool isUsableType(llvm::StructType *Ty) const {
5325 if (Ty->getNumElements() != Elems.size())
5326 return false;
5327 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5328 if (Elems[i] != Ty->getElementType(i))
5329 return false;
5330 return true;
5331 }
5332
5333 // Get the coercion type as a literal struct type.
5334 llvm::Type *getType() const {
5335 if (Elems.size() == 1)
5336 return Elems.front();
5337 else
5338 return llvm::StructType::get(Context, Elems);
5339 }
5340 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005341};
5342} // end anonymous namespace
5343
5344ABIArgInfo
5345SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5346 if (Ty->isVoidType())
5347 return ABIArgInfo::getIgnore();
5348
5349 uint64_t Size = getContext().getTypeSize(Ty);
5350
5351 // Anything too big to fit in registers is passed with an explicit indirect
5352 // pointer / sret pointer.
5353 if (Size > SizeLimit)
5354 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5355
5356 // Treat an enum type as its underlying type.
5357 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5358 Ty = EnumTy->getDecl()->getIntegerType();
5359
5360 // Integer types smaller than a register are extended.
5361 if (Size < 64 && Ty->isIntegerType())
5362 return ABIArgInfo::getExtend();
5363
5364 // Other non-aggregates go in registers.
5365 if (!isAggregateTypeForABI(Ty))
5366 return ABIArgInfo::getDirect();
5367
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005368 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5369 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5370 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5371 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5372
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005373 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005374 // Build a coercion type from the LLVM struct type.
5375 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5376 if (!StrTy)
5377 return ABIArgInfo::getDirect();
5378
5379 CoerceBuilder CB(getVMContext(), getDataLayout());
5380 CB.addStruct(0, StrTy);
5381 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5382
5383 // Try to use the original type for coercion.
5384 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5385
5386 if (CB.InReg)
5387 return ABIArgInfo::getDirectInReg(CoerceTy);
5388 else
5389 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005390}
5391
5392llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5393 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005394 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5395 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5396 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5397 AI.setCoerceToType(ArgTy);
5398
5399 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5400 CGBuilderTy &Builder = CGF.Builder;
5401 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5402 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5403 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5404 llvm::Value *ArgAddr;
5405 unsigned Stride;
5406
5407 switch (AI.getKind()) {
5408 case ABIArgInfo::Expand:
5409 llvm_unreachable("Unsupported ABI kind for va_arg");
5410
5411 case ABIArgInfo::Extend:
5412 Stride = 8;
5413 ArgAddr = Builder
5414 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5415 "extend");
5416 break;
5417
5418 case ABIArgInfo::Direct:
5419 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5420 ArgAddr = Addr;
5421 break;
5422
5423 case ABIArgInfo::Indirect:
5424 Stride = 8;
5425 ArgAddr = Builder.CreateBitCast(Addr,
5426 llvm::PointerType::getUnqual(ArgPtrTy),
5427 "indirect");
5428 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5429 break;
5430
5431 case ABIArgInfo::Ignore:
5432 return llvm::UndefValue::get(ArgPtrTy);
5433 }
5434
5435 // Update VAList.
5436 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5437 Builder.CreateStore(Addr, VAListAddrAsBPP);
5438
5439 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005440}
5441
5442void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5443 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5444 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5445 it != ie; ++it)
5446 it->info = classifyType(it->type, 16 * 8);
5447}
5448
5449namespace {
5450class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5451public:
5452 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5453 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5454};
5455} // end anonymous namespace
5456
5457
Robert Lytton0e076492013-08-13 09:43:10 +00005458//===----------------------------------------------------------------------===//
5459// Xcore ABI Implementation
5460//===----------------------------------------------------------------------===//
5461namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005462class XCoreABIInfo : public DefaultABIInfo {
5463public:
5464 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5465 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5466 CodeGenFunction &CGF) const;
5467};
5468
Robert Lytton0e076492013-08-13 09:43:10 +00005469class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5470public:
5471 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005472 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005473};
Robert Lytton2d196952013-10-11 10:29:34 +00005474} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005475
Robert Lytton7d1db152013-08-19 09:46:39 +00005476llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5477 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005478 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005479
Robert Lytton2d196952013-10-11 10:29:34 +00005480 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005481 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5482 CGF.Int8PtrPtrTy);
5483 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005484
Robert Lytton2d196952013-10-11 10:29:34 +00005485 // Handle the argument.
5486 ABIArgInfo AI = classifyArgumentType(Ty);
5487 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5488 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5489 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005490 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005491 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005492 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005493 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005494 case ABIArgInfo::Expand:
5495 llvm_unreachable("Unsupported ABI kind for va_arg");
5496 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005497 Val = llvm::UndefValue::get(ArgPtrTy);
5498 ArgSize = 0;
5499 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005500 case ABIArgInfo::Extend:
5501 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005502 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5503 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5504 if (ArgSize < 4)
5505 ArgSize = 4;
5506 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005507 case ABIArgInfo::Indirect:
5508 llvm::Value *ArgAddr;
5509 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5510 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005511 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5512 ArgSize = 4;
5513 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005514 }
Robert Lytton2d196952013-10-11 10:29:34 +00005515
5516 // Increment the VAList.
5517 if (ArgSize) {
5518 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5519 Builder.CreateStore(APN, VAListAddrAsBPP);
5520 }
5521 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005522}
Robert Lytton0e076492013-08-13 09:43:10 +00005523
5524//===----------------------------------------------------------------------===//
5525// Driver code
5526//===----------------------------------------------------------------------===//
5527
Chris Lattner2b037972010-07-29 02:01:43 +00005528const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005529 if (TheTargetCodeGenInfo)
5530 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005531
John McCallc8e01702013-04-16 22:48:15 +00005532 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005533 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005534 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005535 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005536
Derek Schuff09338a22012-09-06 17:37:28 +00005537 case llvm::Triple::le32:
5538 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005539 case llvm::Triple::mips:
5540 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005541 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5542
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005543 case llvm::Triple::mips64:
5544 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005545 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5546
Tim Northover9bb857a2013-01-31 12:13:10 +00005547 case llvm::Triple::aarch64:
5548 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5549
Daniel Dunbard59655c2009-09-12 00:59:49 +00005550 case llvm::Triple::arm:
5551 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005552 {
5553 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005554 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005555 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005556 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005557 (CodeGenOpts.FloatABI != "soft" &&
5558 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005559 Kind = ARMABIInfo::AAPCS_VFP;
5560
Derek Schuffa2020962012-10-16 22:30:41 +00005561 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005562 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005563 return *(TheTargetCodeGenInfo =
5564 new NaClARMTargetCodeGenInfo(Types, Kind));
5565 default:
5566 return *(TheTargetCodeGenInfo =
5567 new ARMTargetCodeGenInfo(Types, Kind));
5568 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005569 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005570
John McCallea8d8bb2010-03-11 00:10:12 +00005571 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005572 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005573 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005574 if (Triple.isOSBinFormatELF())
5575 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5576 else
5577 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005578 case llvm::Triple::ppc64le:
5579 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5580 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005581
Peter Collingbournec947aae2012-05-20 23:28:41 +00005582 case llvm::Triple::nvptx:
5583 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005584 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005585
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005586 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005587 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005588
Ulrich Weigand47445072013-05-06 16:26:41 +00005589 case llvm::Triple::systemz:
5590 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5591
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005592 case llvm::Triple::tce:
5593 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5594
Eli Friedman33465822011-07-08 23:31:17 +00005595 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005596 bool IsDarwinVectorABI = Triple.isOSDarwin();
5597 bool IsSmallStructInRegABI =
5598 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5599 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005600
John McCall1fe2a8c2013-06-18 02:46:29 +00005601 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005602 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005603 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005604 IsDarwinVectorABI, IsSmallStructInRegABI,
5605 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005606 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005607 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005608 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005609 new X86_32TargetCodeGenInfo(Types,
5610 IsDarwinVectorABI, IsSmallStructInRegABI,
5611 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005612 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005613 }
Eli Friedman33465822011-07-08 23:31:17 +00005614 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005615
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005616 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005617 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005618
Chris Lattner04dc9572010-08-31 16:44:54 +00005619 switch (Triple.getOS()) {
5620 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005621 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005622 case llvm::Triple::Cygwin:
5623 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005624 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005625 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5626 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005627 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005628 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5629 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005630 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005631 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005632 case llvm::Triple::hexagon:
5633 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005634 case llvm::Triple::sparcv9:
5635 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005636 case llvm::Triple::xcore:
5637 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5638
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005639 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005640}