blob: c538234d00909704214d0a85113bdb761c2366dd [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:
Amara Emerson9dc78782014-01-28 10:56:36 +00003102 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Manman Renb505d332012-10-31 19:02:26 +00003103 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3104 unsigned &AllocatedVFP,
Amara Emerson9dc78782014-01-28 10:56:36 +00003105 bool &IsHA, bool isVariadic) 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 };
Amara Emerson9dc78782014-01-28 10:56:36 +00003201 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
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;
Amara Emerson9dc78782014-01-28 10:56:36 +00003209 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA, FI.isVariadic());
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.
Amara Emerson9dc78782014-01-28 10:56:36 +00003213 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3214 // and the callee is not variadic.
Manman Ren2a523d82012-10-30 23:21:41 +00003215 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3216 llvm::Type *PaddingTy = llvm::ArrayType::get(
3217 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3218 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3219 }
3220 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003221
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003222 // Always honor user-specified calling convention.
3223 if (FI.getCallingConvention() != llvm::CallingConv::C)
3224 return;
3225
John McCall882987f2013-02-28 19:01:20 +00003226 llvm::CallingConv::ID cc = getRuntimeCC();
3227 if (cc != llvm::CallingConv::C)
3228 FI.setEffectiveCallingConvention(cc);
3229}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003230
John McCall882987f2013-02-28 19:01:20 +00003231/// Return the default calling convention that LLVM will use.
3232llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3233 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003234 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003235 return llvm::CallingConv::ARM_AAPCS_VFP;
3236 else if (isEABI())
3237 return llvm::CallingConv::ARM_AAPCS;
3238 else
3239 return llvm::CallingConv::ARM_APCS;
3240}
3241
3242/// Return the calling convention that our ABI would like us to use
3243/// as the C calling convention.
3244llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003245 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003246 case APCS: return llvm::CallingConv::ARM_APCS;
3247 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3248 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003249 }
John McCall882987f2013-02-28 19:01:20 +00003250 llvm_unreachable("bad ABI kind");
3251}
3252
3253void ARMABIInfo::setRuntimeCC() {
3254 assert(getRuntimeCC() == llvm::CallingConv::C);
3255
3256 // Don't muddy up the IR with a ton of explicit annotations if
3257 // they'd just match what LLVM will infer from the triple.
3258 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3259 if (abiCC != getLLVMDefaultCC())
3260 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003261}
3262
Bob Wilsone826a2a2011-08-03 05:58:22 +00003263/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3264/// aggregate. If HAMembers is non-null, the number of base elements
3265/// contained in the type is returned through it; this is used for the
3266/// recursive calls that check aggregate component types.
3267static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3268 ASTContext &Context,
3269 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003270 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003271 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3272 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3273 return false;
3274 Members *= AT->getSize().getZExtValue();
3275 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3276 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003277 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003278 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003279
Bob Wilsone826a2a2011-08-03 05:58:22 +00003280 Members = 0;
3281 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3282 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003283 const FieldDecl *FD = *i;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003284 uint64_t FldMembers;
3285 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3286 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003287
3288 Members = (RD->isUnion() ?
3289 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003290 }
3291 } else {
3292 Members = 1;
3293 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3294 Members = 2;
3295 Ty = CT->getElementType();
3296 }
3297
3298 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3299 // double, or 64-bit or 128-bit vectors.
3300 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3301 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003302 BT->getKind() != BuiltinType::Double &&
3303 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003304 return false;
3305 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3306 unsigned VecSize = Context.getTypeSize(VT);
3307 if (VecSize != 64 && VecSize != 128)
3308 return false;
3309 } else {
3310 return false;
3311 }
3312
3313 // The base type must be the same for all members. Vector types of the
3314 // same total size are treated as being equivalent here.
3315 const Type *TyPtr = Ty.getTypePtr();
3316 if (!Base)
3317 Base = TyPtr;
3318 if (Base != TyPtr &&
3319 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3320 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3321 return false;
3322 }
3323
3324 // Homogeneous Aggregates can have at most 4 members of the base type.
3325 if (HAMembers)
3326 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003327
3328 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003329}
3330
Manman Renb505d332012-10-31 19:02:26 +00003331/// markAllocatedVFPs - update VFPRegs according to the alignment and
3332/// number of VFP registers (unit is S register) requested.
3333static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3334 unsigned Alignment,
3335 unsigned NumRequired) {
3336 // Early Exit.
3337 if (AllocatedVFP >= 16)
3338 return;
3339 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3340 // VFP registers of the appropriate type unallocated then the argument is
3341 // allocated to the lowest-numbered sequence of such registers.
3342 for (unsigned I = 0; I < 16; I += Alignment) {
3343 bool FoundSlot = true;
3344 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3345 if (J >= 16 || VFPRegs[J]) {
3346 FoundSlot = false;
3347 break;
3348 }
3349 if (FoundSlot) {
3350 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3351 VFPRegs[J] = 1;
3352 AllocatedVFP += NumRequired;
3353 return;
3354 }
3355 }
3356 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3357 // unallocated are marked as unavailable.
3358 for (unsigned I = 0; I < 16; I++)
3359 VFPRegs[I] = 1;
3360 AllocatedVFP = 17; // We do not have enough VFP registers.
3361}
3362
3363ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3364 unsigned &AllocatedVFP,
Amara Emerson9dc78782014-01-28 10:56:36 +00003365 bool &IsHA, bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003366 // We update number of allocated VFPs according to
3367 // 6.1.2.1 The following argument types are VFP CPRCs:
3368 // A single-precision floating-point type (including promoted
3369 // half-precision types); A double-precision floating-point type;
3370 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3371 // with a Base Type of a single- or double-precision floating-point type,
3372 // 64-bit containerized vectors or 128-bit containerized vectors with one
3373 // to four Elements.
3374
Manman Renfef9e312012-10-16 19:18:39 +00003375 // Handle illegal vector types here.
3376 if (isIllegalVectorType(Ty)) {
3377 uint64_t Size = getContext().getTypeSize(Ty);
3378 if (Size <= 32) {
3379 llvm::Type *ResType =
3380 llvm::Type::getInt32Ty(getVMContext());
3381 return ABIArgInfo::getDirect(ResType);
3382 }
3383 if (Size == 64) {
3384 llvm::Type *ResType = llvm::VectorType::get(
3385 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Renb505d332012-10-31 19:02:26 +00003386 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renfef9e312012-10-16 19:18:39 +00003387 return ABIArgInfo::getDirect(ResType);
3388 }
3389 if (Size == 128) {
3390 llvm::Type *ResType = llvm::VectorType::get(
3391 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Renb505d332012-10-31 19:02:26 +00003392 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Renfef9e312012-10-16 19:18:39 +00003393 return ABIArgInfo::getDirect(ResType);
3394 }
3395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3396 }
Manman Renb505d332012-10-31 19:02:26 +00003397 // Update VFPRegs for legal vector types.
Manman Ren2a523d82012-10-30 23:21:41 +00003398 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3399 uint64_t Size = getContext().getTypeSize(VT);
3400 // Size of a legal vector should be power of 2 and above 64.
Manman Renb505d332012-10-31 19:02:26 +00003401 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Ren2a523d82012-10-30 23:21:41 +00003402 }
Manman Renb505d332012-10-31 19:02:26 +00003403 // Update VFPRegs for floating point types.
Manman Ren2a523d82012-10-30 23:21:41 +00003404 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3405 if (BT->getKind() == BuiltinType::Half ||
3406 BT->getKind() == BuiltinType::Float)
Manman Renb505d332012-10-31 19:02:26 +00003407 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Ren2a523d82012-10-30 23:21:41 +00003408 if (BT->getKind() == BuiltinType::Double ||
Manman Renb505d332012-10-31 19:02:26 +00003409 BT->getKind() == BuiltinType::LongDouble)
3410 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003411 }
Manman Renfef9e312012-10-16 19:18:39 +00003412
John McCalla1dee5302010-08-22 10:59:02 +00003413 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003414 // Treat an enum type as its underlying type.
3415 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3416 Ty = EnumTy->getDecl()->getIntegerType();
3417
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003418 return (Ty->isPromotableIntegerType() ?
3419 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003420 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003421
Mark Lacey3825e832013-10-06 01:33:34 +00003422 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Tim Northover1060eae2013-06-21 22:49:34 +00003423 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3424
Daniel Dunbar09d33622009-09-14 21:54:03 +00003425 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003426 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003427 return ABIArgInfo::getIgnore();
3428
Amara Emerson9dc78782014-01-28 10:56:36 +00003429 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00003430 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3431 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003432 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003433 uint64_t Members = 0;
3434 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003435 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003436 // Base can be a floating-point or a vector.
3437 if (Base->isVectorType()) {
3438 // ElementSize is in number of floats.
3439 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Ren77b02382012-11-06 19:05:29 +00003440 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3441 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003442 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Renb505d332012-10-31 19:02:26 +00003443 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003444 else {
3445 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3446 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Renb505d332012-10-31 19:02:26 +00003447 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003448 }
3449 IsHA = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003450 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003451 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003452 }
3453
Manman Ren6c30e132012-08-13 21:23:55 +00003454 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003455 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3456 // most 8-byte. We realign the indirect argument if type alignment is bigger
3457 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003458 uint64_t ABIAlign = 4;
3459 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3460 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3461 getABIKind() == ARMABIInfo::AAPCS)
3462 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003463 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3464 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003465 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003466 }
3467
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003468 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003469 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003470 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003471 // FIXME: Try to match the types of the arguments more accurately where
3472 // we can.
3473 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003474 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3475 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00003476 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003477 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3478 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003479 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003480
Chris Lattnera5f58b02011-07-09 17:41:47 +00003481 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003482 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003483 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003484}
3485
Chris Lattner458b2aa2010-07-29 02:16:43 +00003486static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003487 llvm::LLVMContext &VMContext) {
3488 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3489 // is called integer-like if its size is less than or equal to one word, and
3490 // the offset of each of its addressable sub-fields is zero.
3491
3492 uint64_t Size = Context.getTypeSize(Ty);
3493
3494 // Check that the type fits in a word.
3495 if (Size > 32)
3496 return false;
3497
3498 // FIXME: Handle vector types!
3499 if (Ty->isVectorType())
3500 return false;
3501
Daniel Dunbard53bac72009-09-14 02:20:34 +00003502 // Float types are never treated as "integer like".
3503 if (Ty->isRealFloatingType())
3504 return false;
3505
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003506 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003507 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003508 return true;
3509
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003510 // Small complex integer types are "integer like".
3511 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3512 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003513
3514 // Single element and zero sized arrays should be allowed, by the definition
3515 // above, but they are not.
3516
3517 // Otherwise, it must be a record type.
3518 const RecordType *RT = Ty->getAs<RecordType>();
3519 if (!RT) return false;
3520
3521 // Ignore records with flexible arrays.
3522 const RecordDecl *RD = RT->getDecl();
3523 if (RD->hasFlexibleArrayMember())
3524 return false;
3525
3526 // Check that all sub-fields are at offset 0, and are themselves "integer
3527 // like".
3528 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3529
3530 bool HadField = false;
3531 unsigned idx = 0;
3532 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3533 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003534 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003535
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003536 // Bit-fields are not addressable, we only need to verify they are "integer
3537 // like". We still have to disallow a subsequent non-bitfield, for example:
3538 // struct { int : 0; int x }
3539 // is non-integer like according to gcc.
3540 if (FD->isBitField()) {
3541 if (!RD->isUnion())
3542 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003543
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003544 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3545 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003546
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003547 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003548 }
3549
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003550 // Check if this field is at offset 0.
3551 if (Layout.getFieldOffset(idx) != 0)
3552 return false;
3553
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003554 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3555 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003556
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003557 // Only allow at most one field in a structure. This doesn't match the
3558 // wording above, but follows gcc in situations with a field following an
3559 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003560 if (!RD->isUnion()) {
3561 if (HadField)
3562 return false;
3563
3564 HadField = true;
3565 }
3566 }
3567
3568 return true;
3569}
3570
Amara Emerson9dc78782014-01-28 10:56:36 +00003571ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003572 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003573 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003574
Daniel Dunbar19964db2010-09-23 01:54:32 +00003575 // Large vector types should be returned via memory.
3576 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3577 return ABIArgInfo::getIndirect(0);
3578
John McCalla1dee5302010-08-22 10:59:02 +00003579 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003580 // Treat an enum type as its underlying type.
3581 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3582 RetTy = EnumTy->getDecl()->getIntegerType();
3583
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003584 return (RetTy->isPromotableIntegerType() ?
3585 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003586 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003587
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003588 // Structures with either a non-trivial destructor or a non-trivial
3589 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00003590 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003591 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3592
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003593 // Are we following APCS?
3594 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003595 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003596 return ABIArgInfo::getIgnore();
3597
Daniel Dunbareedf1512010-02-01 23:31:19 +00003598 // Complex types are all returned as packed integers.
3599 //
3600 // FIXME: Consider using 2 x vector types if the back end handles them
3601 // correctly.
3602 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003603 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003604 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003605
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003606 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003607 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003608 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003609 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003610 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003611 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003612 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003613 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3614 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003615 }
3616
3617 // Otherwise return in memory.
3618 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003619 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003620
3621 // Otherwise this is an AAPCS variant.
3622
Chris Lattner458b2aa2010-07-29 02:16:43 +00003623 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003624 return ABIArgInfo::getIgnore();
3625
Bob Wilson1d9269a2011-11-02 04:51:36 +00003626 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00003627 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson1d9269a2011-11-02 04:51:36 +00003628 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003629 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3630 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003631 // Homogeneous Aggregates are returned directly.
3632 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003633 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003634 }
3635
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003636 // Aggregates <= 4 bytes are returned in r0; other aggregates
3637 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003638 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003639 if (Size <= 32) {
3640 // Return in the smallest viable integer type.
3641 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003642 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003643 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003644 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3645 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003646 }
3647
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003648 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003649}
3650
Manman Renfef9e312012-10-16 19:18:39 +00003651/// isIllegalVector - check whether Ty is an illegal vector type.
3652bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3653 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3654 // Check whether VT is legal.
3655 unsigned NumElements = VT->getNumElements();
3656 uint64_t Size = getContext().getTypeSize(VT);
3657 // NumElements should be power of 2.
3658 if ((NumElements & (NumElements - 1)) != 0)
3659 return true;
3660 // Size should be greater than 32 bits.
3661 return Size <= 32;
3662 }
3663 return false;
3664}
3665
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003666llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003667 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003668 llvm::Type *BP = CGF.Int8PtrTy;
3669 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003670
3671 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003672 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003673 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003674
Tim Northover1711cc92013-06-21 23:05:33 +00003675 if (isEmptyRecord(getContext(), Ty, true)) {
3676 // These are ignored for parameter passing purposes.
3677 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3678 return Builder.CreateBitCast(Addr, PTy);
3679 }
3680
Manman Rencca54d02012-10-16 19:01:37 +00003681 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003682 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003683 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003684
3685 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3686 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003687 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3688 getABIKind() == ARMABIInfo::AAPCS)
3689 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3690 else
3691 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003692 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3693 if (isIllegalVectorType(Ty) && Size > 16) {
3694 IsIndirect = true;
3695 Size = 4;
3696 TyAlign = 4;
3697 }
Manman Rencca54d02012-10-16 19:01:37 +00003698
3699 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003700 if (TyAlign > 4) {
3701 assert((TyAlign & (TyAlign - 1)) == 0 &&
3702 "Alignment is not power of 2!");
3703 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3704 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3705 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003706 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003707 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003708
3709 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003710 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003711 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003712 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003713 "ap.next");
3714 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3715
Manman Renfef9e312012-10-16 19:18:39 +00003716 if (IsIndirect)
3717 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003718 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003719 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3720 // may not be correctly aligned for the vector type. We create an aligned
3721 // temporary space and copy the content over from ap.cur to the temporary
3722 // space. This is necessary if the natural alignment of the type is greater
3723 // than the ABI alignment.
3724 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3725 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3726 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3727 "var.align");
3728 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3729 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3730 Builder.CreateMemCpy(Dst, Src,
3731 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3732 TyAlign, false);
3733 Addr = AlignedTemp; //The content is in aligned location.
3734 }
3735 llvm::Type *PTy =
3736 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3737 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3738
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003739 return AddrTyped;
3740}
3741
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003742namespace {
3743
Derek Schuffa2020962012-10-16 22:30:41 +00003744class NaClARMABIInfo : public ABIInfo {
3745 public:
3746 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3747 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3748 virtual void computeInfo(CGFunctionInfo &FI) const;
3749 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3750 CodeGenFunction &CGF) const;
3751 private:
3752 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3753 ARMABIInfo NInfo; // Used for everything else.
3754};
3755
3756class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3757 public:
3758 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3759 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3760};
3761
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003762}
3763
Derek Schuffa2020962012-10-16 22:30:41 +00003764void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3765 if (FI.getASTCallingConvention() == CC_PnaclCall)
3766 PInfo.computeInfo(FI);
3767 else
3768 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3769}
3770
3771llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3772 CodeGenFunction &CGF) const {
3773 // Always use the native convention; calling pnacl-style varargs functions
3774 // is unsupported.
3775 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3776}
3777
Chris Lattner0cf24192010-06-28 20:05:43 +00003778//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003779// AArch64 ABI Implementation
3780//===----------------------------------------------------------------------===//
3781
3782namespace {
3783
3784class AArch64ABIInfo : public ABIInfo {
3785public:
3786 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3787
3788private:
3789 // The AArch64 PCS is explicit about return types and argument types being
3790 // handled identically, so we don't need to draw a distinction between
3791 // Argument and Return classification.
3792 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3793 int &FreeVFPRegs) const;
3794
3795 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3796 llvm::Type *DirectTy = 0) const;
3797
3798 virtual void computeInfo(CGFunctionInfo &FI) const;
3799
3800 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3801 CodeGenFunction &CGF) const;
3802};
3803
3804class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3805public:
3806 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3807 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3808
3809 const AArch64ABIInfo &getABIInfo() const {
3810 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3811 }
3812
3813 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3814 return 31;
3815 }
3816
3817 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3818 llvm::Value *Address) const {
3819 // 0-31 are x0-x30 and sp: 8 bytes each
3820 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3821 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3822
3823 // 64-95 are v0-v31: 16 bytes each
3824 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3825 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3826
3827 return false;
3828 }
3829
3830};
3831
3832}
3833
3834void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3835 int FreeIntRegs = 8, FreeVFPRegs = 8;
3836
3837 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3838 FreeIntRegs, FreeVFPRegs);
3839
3840 FreeIntRegs = FreeVFPRegs = 8;
3841 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3842 it != ie; ++it) {
3843 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3844
3845 }
3846}
3847
3848ABIArgInfo
3849AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3850 bool IsInt, llvm::Type *DirectTy) const {
3851 if (FreeRegs >= RegsNeeded) {
3852 FreeRegs -= RegsNeeded;
3853 return ABIArgInfo::getDirect(DirectTy);
3854 }
3855
3856 llvm::Type *Padding = 0;
3857
3858 // We need padding so that later arguments don't get filled in anyway. That
3859 // wouldn't happen if only ByVal arguments followed in the same category, but
3860 // a large structure will simply seem to be a pointer as far as LLVM is
3861 // concerned.
3862 if (FreeRegs > 0) {
3863 if (IsInt)
3864 Padding = llvm::Type::getInt64Ty(getVMContext());
3865 else
3866 Padding = llvm::Type::getFloatTy(getVMContext());
3867
3868 // Either [N x i64] or [N x float].
3869 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3870 FreeRegs = 0;
3871 }
3872
3873 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3874 /*IsByVal=*/ true, /*Realign=*/ false,
3875 Padding);
3876}
3877
3878
3879ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3880 int &FreeIntRegs,
3881 int &FreeVFPRegs) const {
3882 // Can only occurs for return, but harmless otherwise.
3883 if (Ty->isVoidType())
3884 return ABIArgInfo::getIgnore();
3885
3886 // Large vector types should be returned via memory. There's no such concept
3887 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3888 // classified they'd go into memory (see B.3).
3889 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3890 if (FreeIntRegs > 0)
3891 --FreeIntRegs;
3892 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3893 }
3894
3895 // All non-aggregate LLVM types have a concrete ABI representation so they can
3896 // be passed directly. After this block we're guaranteed to be in a
3897 // complicated case.
3898 if (!isAggregateTypeForABI(Ty)) {
3899 // Treat an enum type as its underlying type.
3900 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3901 Ty = EnumTy->getDecl()->getIntegerType();
3902
3903 if (Ty->isFloatingType() || Ty->isVectorType())
3904 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3905
3906 assert(getContext().getTypeSize(Ty) <= 128 &&
3907 "unexpectedly large scalar type");
3908
3909 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3910
3911 // If the type may need padding registers to ensure "alignment", we must be
3912 // careful when this is accounted for. Increasing the effective size covers
3913 // all cases.
3914 if (getContext().getTypeAlign(Ty) == 128)
3915 RegsNeeded += FreeIntRegs % 2 != 0;
3916
3917 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3918 }
3919
Mark Lacey3825e832013-10-06 01:33:34 +00003920 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003921 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00003922 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003923 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00003924 }
3925
3926 if (isEmptyRecord(getContext(), Ty, true)) {
3927 if (!getContext().getLangOpts().CPlusPlus) {
3928 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3929 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3930 // the object for parameter-passsing purposes.
3931 return ABIArgInfo::getIgnore();
3932 }
3933
3934 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3935 // description of va_arg in the PCS require that an empty struct does
3936 // actually occupy space for parameter-passing. I'm hoping for a
3937 // clarification giving an explicit paragraph to point to in future.
3938 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3939 llvm::Type::getInt8Ty(getVMContext()));
3940 }
3941
3942 // Homogeneous vector aggregates get passed in registers or on the stack.
3943 const Type *Base = 0;
3944 uint64_t NumMembers = 0;
3945 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3946 assert(Base && "Base class should be set for homogeneous aggregate");
3947 // Homogeneous aggregates are passed and returned directly.
3948 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3949 /*IsInt=*/ false);
3950 }
3951
3952 uint64_t Size = getContext().getTypeSize(Ty);
3953 if (Size <= 128) {
3954 // Small structs can use the same direct type whether they're in registers
3955 // or on the stack.
3956 llvm::Type *BaseTy;
3957 unsigned NumBases;
3958 int SizeInRegs = (Size + 63) / 64;
3959
3960 if (getContext().getTypeAlign(Ty) == 128) {
3961 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3962 NumBases = 1;
3963
3964 // If the type may need padding registers to ensure "alignment", we must
3965 // be careful when this is accounted for. Increasing the effective size
3966 // covers all cases.
3967 SizeInRegs += FreeIntRegs % 2 != 0;
3968 } else {
3969 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3970 NumBases = SizeInRegs;
3971 }
3972 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3973
3974 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3975 /*IsInt=*/ true, DirectTy);
3976 }
3977
3978 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3979 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3980 --FreeIntRegs;
3981 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3982}
3983
3984llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3985 CodeGenFunction &CGF) const {
3986 // The AArch64 va_list type and handling is specified in the Procedure Call
3987 // Standard, section B.4:
3988 //
3989 // struct {
3990 // void *__stack;
3991 // void *__gr_top;
3992 // void *__vr_top;
3993 // int __gr_offs;
3994 // int __vr_offs;
3995 // };
3996
3997 assert(!CGF.CGM.getDataLayout().isBigEndian()
3998 && "va_arg not implemented for big-endian AArch64");
3999
4000 int FreeIntRegs = 8, FreeVFPRegs = 8;
4001 Ty = CGF.getContext().getCanonicalType(Ty);
4002 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4003
4004 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4005 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4006 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4007 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4008
4009 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4010 int reg_top_index;
4011 int RegSize;
4012 if (FreeIntRegs < 8) {
4013 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4014 // 3 is the field number of __gr_offs
4015 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4016 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4017 reg_top_index = 1; // field number for __gr_top
4018 RegSize = 8 * (8 - FreeIntRegs);
4019 } else {
4020 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4021 // 4 is the field number of __vr_offs.
4022 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4023 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4024 reg_top_index = 2; // field number for __vr_top
4025 RegSize = 16 * (8 - FreeVFPRegs);
4026 }
4027
4028 //=======================================
4029 // Find out where argument was passed
4030 //=======================================
4031
4032 // If reg_offs >= 0 we're already using the stack for this type of
4033 // argument. We don't want to keep updating reg_offs (in case it overflows,
4034 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4035 // whatever they get).
4036 llvm::Value *UsingStack = 0;
4037 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4038 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4039
4040 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4041
4042 // Otherwise, at least some kind of argument could go in these registers, the
4043 // quesiton is whether this particular type is too big.
4044 CGF.EmitBlock(MaybeRegBlock);
4045
4046 // Integer arguments may need to correct register alignment (for example a
4047 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4048 // align __gr_offs to calculate the potential address.
4049 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4050 int Align = getContext().getTypeAlign(Ty) / 8;
4051
4052 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4053 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4054 "align_regoffs");
4055 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4056 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4057 "aligned_regoffs");
4058 }
4059
4060 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4061 llvm::Value *NewOffset = 0;
4062 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4063 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4064 "new_reg_offs");
4065 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4066
4067 // Now we're in a position to decide whether this argument really was in
4068 // registers or not.
4069 llvm::Value *InRegs = 0;
4070 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4071 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4072 "inreg");
4073
4074 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4075
4076 //=======================================
4077 // Argument was in registers
4078 //=======================================
4079
4080 // Now we emit the code for if the argument was originally passed in
4081 // registers. First start the appropriate block:
4082 CGF.EmitBlock(InRegBlock);
4083
4084 llvm::Value *reg_top_p = 0, *reg_top = 0;
4085 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4086 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4087 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4088 llvm::Value *RegAddr = 0;
4089 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4090
4091 if (!AI.isDirect()) {
4092 // If it's been passed indirectly (actually a struct), whatever we find from
4093 // stored registers or on the stack will actually be a struct **.
4094 MemTy = llvm::PointerType::getUnqual(MemTy);
4095 }
4096
4097 const Type *Base = 0;
4098 uint64_t NumMembers;
4099 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4100 && NumMembers > 1) {
4101 // Homogeneous aggregates passed in registers will have their elements split
4102 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4103 // qN+1, ...). We reload and store into a temporary local variable
4104 // contiguously.
4105 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4106 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4107 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4108 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4109
4110 for (unsigned i = 0; i < NumMembers; ++i) {
4111 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4112 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4113 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4114 llvm::PointerType::getUnqual(BaseTy));
4115 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4116
4117 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4118 CGF.Builder.CreateStore(Elem, StoreAddr);
4119 }
4120
4121 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4122 } else {
4123 // Otherwise the object is contiguous in memory
4124 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4125 }
4126
4127 CGF.EmitBranch(ContBlock);
4128
4129 //=======================================
4130 // Argument was on the stack
4131 //=======================================
4132 CGF.EmitBlock(OnStackBlock);
4133
4134 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4135 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4136 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4137
4138 // Again, stack arguments may need realigmnent. In this case both integer and
4139 // floating-point ones might be affected.
4140 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4141 int Align = getContext().getTypeAlign(Ty) / 8;
4142
4143 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4144
4145 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4146 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4147 "align_stack");
4148 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4149 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4150 "align_stack");
4151
4152 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4153 }
4154
4155 uint64_t StackSize;
4156 if (AI.isDirect())
4157 StackSize = getContext().getTypeSize(Ty) / 8;
4158 else
4159 StackSize = 8;
4160
4161 // All stack slots are 8 bytes
4162 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4163
4164 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4165 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4166 "new_stack");
4167
4168 // Write the new value of __stack for the next call to va_arg
4169 CGF.Builder.CreateStore(NewStack, stack_p);
4170
4171 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4172
4173 CGF.EmitBranch(ContBlock);
4174
4175 //=======================================
4176 // Tidy up
4177 //=======================================
4178 CGF.EmitBlock(ContBlock);
4179
4180 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4181 ResAddr->addIncoming(RegAddr, InRegBlock);
4182 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4183
4184 if (AI.isDirect())
4185 return ResAddr;
4186
4187 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4188}
4189
4190//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004191// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004192//===----------------------------------------------------------------------===//
4193
4194namespace {
4195
Justin Holewinski83e96682012-05-24 17:43:12 +00004196class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004197public:
Justin Holewinski36837432013-03-30 14:38:24 +00004198 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004199
4200 ABIArgInfo classifyReturnType(QualType RetTy) const;
4201 ABIArgInfo classifyArgumentType(QualType Ty) const;
4202
4203 virtual void computeInfo(CGFunctionInfo &FI) const;
4204 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4205 CodeGenFunction &CFG) const;
4206};
4207
Justin Holewinski83e96682012-05-24 17:43:12 +00004208class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004209public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004210 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4211 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski38031972011-10-05 17:58:44 +00004212
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004213 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4214 CodeGen::CodeGenModule &M) const;
Justin Holewinski36837432013-03-30 14:38:24 +00004215private:
4216 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004217};
4218
Justin Holewinski83e96682012-05-24 17:43:12 +00004219ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004220 if (RetTy->isVoidType())
4221 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004222
4223 // note: this is different from default ABI
4224 if (!RetTy->isScalarType())
4225 return ABIArgInfo::getDirect();
4226
4227 // Treat an enum type as its underlying type.
4228 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4229 RetTy = EnumTy->getDecl()->getIntegerType();
4230
4231 return (RetTy->isPromotableIntegerType() ?
4232 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004233}
4234
Justin Holewinski83e96682012-05-24 17:43:12 +00004235ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004236 // Treat an enum type as its underlying type.
4237 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4238 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004239
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004240 return (Ty->isPromotableIntegerType() ?
4241 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004242}
4243
Justin Holewinski83e96682012-05-24 17:43:12 +00004244void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004245 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4246 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4247 it != ie; ++it)
4248 it->info = classifyArgumentType(it->type);
4249
4250 // Always honor user-specified calling convention.
4251 if (FI.getCallingConvention() != llvm::CallingConv::C)
4252 return;
4253
John McCall882987f2013-02-28 19:01:20 +00004254 FI.setEffectiveCallingConvention(getRuntimeCC());
4255}
4256
Justin Holewinski83e96682012-05-24 17:43:12 +00004257llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4258 CodeGenFunction &CFG) const {
4259 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004260}
4261
Justin Holewinski83e96682012-05-24 17:43:12 +00004262void NVPTXTargetCodeGenInfo::
4263SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4264 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004265 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4266 if (!FD) return;
4267
4268 llvm::Function *F = cast<llvm::Function>(GV);
4269
4270 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004271 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004272 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004273 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004274 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004275 // OpenCL __kernel functions get kernel metadata
4276 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004277 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004278 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004279 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004280 }
Justin Holewinski38031972011-10-05 17:58:44 +00004281
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004282 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004283 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004284 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004285 // __global__ functions cannot be called from the device, we do not
4286 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004287 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004288 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004289 }
4290}
4291
Justin Holewinski36837432013-03-30 14:38:24 +00004292void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4293 llvm::Module *M = F->getParent();
4294 llvm::LLVMContext &Ctx = M->getContext();
4295
4296 // Get "nvvm.annotations" metadata node
4297 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4298
4299 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4300 llvm::SmallVector<llvm::Value *, 3> MDVals;
4301 MDVals.push_back(F);
4302 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4303 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4304
4305 // Append metadata to nvvm.annotations
4306 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4307}
4308
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004309}
4310
4311//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004312// SystemZ ABI Implementation
4313//===----------------------------------------------------------------------===//
4314
4315namespace {
4316
4317class SystemZABIInfo : public ABIInfo {
4318public:
4319 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4320
4321 bool isPromotableIntegerType(QualType Ty) const;
4322 bool isCompoundType(QualType Ty) const;
4323 bool isFPArgumentType(QualType Ty) const;
4324
4325 ABIArgInfo classifyReturnType(QualType RetTy) const;
4326 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4327
4328 virtual void computeInfo(CGFunctionInfo &FI) const {
4329 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4330 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4331 it != ie; ++it)
4332 it->info = classifyArgumentType(it->type);
4333 }
4334
4335 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4336 CodeGenFunction &CGF) const;
4337};
4338
4339class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4340public:
4341 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4342 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4343};
4344
4345}
4346
4347bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4348 // Treat an enum type as its underlying type.
4349 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4350 Ty = EnumTy->getDecl()->getIntegerType();
4351
4352 // Promotable integer types are required to be promoted by the ABI.
4353 if (Ty->isPromotableIntegerType())
4354 return true;
4355
4356 // 32-bit values must also be promoted.
4357 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4358 switch (BT->getKind()) {
4359 case BuiltinType::Int:
4360 case BuiltinType::UInt:
4361 return true;
4362 default:
4363 return false;
4364 }
4365 return false;
4366}
4367
4368bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4369 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4370}
4371
4372bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4373 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4374 switch (BT->getKind()) {
4375 case BuiltinType::Float:
4376 case BuiltinType::Double:
4377 return true;
4378 default:
4379 return false;
4380 }
4381
4382 if (const RecordType *RT = Ty->getAsStructureType()) {
4383 const RecordDecl *RD = RT->getDecl();
4384 bool Found = false;
4385
4386 // If this is a C++ record, check the bases first.
4387 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4388 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4389 E = CXXRD->bases_end(); I != E; ++I) {
4390 QualType Base = I->getType();
4391
4392 // Empty bases don't affect things either way.
4393 if (isEmptyRecord(getContext(), Base, true))
4394 continue;
4395
4396 if (Found)
4397 return false;
4398 Found = isFPArgumentType(Base);
4399 if (!Found)
4400 return false;
4401 }
4402
4403 // Check the fields.
4404 for (RecordDecl::field_iterator I = RD->field_begin(),
4405 E = RD->field_end(); I != E; ++I) {
4406 const FieldDecl *FD = *I;
4407
4408 // Empty bitfields don't affect things either way.
4409 // Unlike isSingleElementStruct(), empty structure and array fields
4410 // do count. So do anonymous bitfields that aren't zero-sized.
4411 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4412 return true;
4413
4414 // Unlike isSingleElementStruct(), arrays do not count.
4415 // Nested isFPArgumentType structures still do though.
4416 if (Found)
4417 return false;
4418 Found = isFPArgumentType(FD->getType());
4419 if (!Found)
4420 return false;
4421 }
4422
4423 // Unlike isSingleElementStruct(), trailing padding is allowed.
4424 // An 8-byte aligned struct s { float f; } is passed as a double.
4425 return Found;
4426 }
4427
4428 return false;
4429}
4430
4431llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4432 CodeGenFunction &CGF) const {
4433 // Assume that va_list type is correct; should be pointer to LLVM type:
4434 // struct {
4435 // i64 __gpr;
4436 // i64 __fpr;
4437 // i8 *__overflow_arg_area;
4438 // i8 *__reg_save_area;
4439 // };
4440
4441 // Every argument occupies 8 bytes and is passed by preference in either
4442 // GPRs or FPRs.
4443 Ty = CGF.getContext().getCanonicalType(Ty);
4444 ABIArgInfo AI = classifyArgumentType(Ty);
4445 bool InFPRs = isFPArgumentType(Ty);
4446
4447 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4448 bool IsIndirect = AI.isIndirect();
4449 unsigned UnpaddedBitSize;
4450 if (IsIndirect) {
4451 APTy = llvm::PointerType::getUnqual(APTy);
4452 UnpaddedBitSize = 64;
4453 } else
4454 UnpaddedBitSize = getContext().getTypeSize(Ty);
4455 unsigned PaddedBitSize = 64;
4456 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4457
4458 unsigned PaddedSize = PaddedBitSize / 8;
4459 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4460
4461 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4462 if (InFPRs) {
4463 MaxRegs = 4; // Maximum of 4 FPR arguments
4464 RegCountField = 1; // __fpr
4465 RegSaveIndex = 16; // save offset for f0
4466 RegPadding = 0; // floats are passed in the high bits of an FPR
4467 } else {
4468 MaxRegs = 5; // Maximum of 5 GPR arguments
4469 RegCountField = 0; // __gpr
4470 RegSaveIndex = 2; // save offset for r2
4471 RegPadding = Padding; // values are passed in the low bits of a GPR
4472 }
4473
4474 llvm::Value *RegCountPtr =
4475 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4476 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4477 llvm::Type *IndexTy = RegCount->getType();
4478 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4479 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4480 "fits_in_regs");
4481
4482 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4483 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4484 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4485 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4486
4487 // Emit code to load the value if it was passed in registers.
4488 CGF.EmitBlock(InRegBlock);
4489
4490 // Work out the address of an argument register.
4491 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4492 llvm::Value *ScaledRegCount =
4493 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4494 llvm::Value *RegBase =
4495 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4496 llvm::Value *RegOffset =
4497 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4498 llvm::Value *RegSaveAreaPtr =
4499 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4500 llvm::Value *RegSaveArea =
4501 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4502 llvm::Value *RawRegAddr =
4503 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4504 llvm::Value *RegAddr =
4505 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4506
4507 // Update the register count
4508 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4509 llvm::Value *NewRegCount =
4510 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4511 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4512 CGF.EmitBranch(ContBlock);
4513
4514 // Emit code to load the value if it was passed in memory.
4515 CGF.EmitBlock(InMemBlock);
4516
4517 // Work out the address of a stack argument.
4518 llvm::Value *OverflowArgAreaPtr =
4519 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4520 llvm::Value *OverflowArgArea =
4521 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4522 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4523 llvm::Value *RawMemAddr =
4524 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4525 llvm::Value *MemAddr =
4526 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4527
4528 // Update overflow_arg_area_ptr pointer
4529 llvm::Value *NewOverflowArgArea =
4530 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4531 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4532 CGF.EmitBranch(ContBlock);
4533
4534 // Return the appropriate result.
4535 CGF.EmitBlock(ContBlock);
4536 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4537 ResAddr->addIncoming(RegAddr, InRegBlock);
4538 ResAddr->addIncoming(MemAddr, InMemBlock);
4539
4540 if (IsIndirect)
4541 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4542
4543 return ResAddr;
4544}
4545
John McCall1fe2a8c2013-06-18 02:46:29 +00004546bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4547 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4548 assert(Triple.getArch() == llvm::Triple::x86);
4549
4550 switch (Opts.getStructReturnConvention()) {
4551 case CodeGenOptions::SRCK_Default:
4552 break;
4553 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4554 return false;
4555 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4556 return true;
4557 }
4558
4559 if (Triple.isOSDarwin())
4560 return true;
4561
4562 switch (Triple.getOS()) {
4563 case llvm::Triple::Cygwin:
4564 case llvm::Triple::MinGW32:
4565 case llvm::Triple::AuroraUX:
4566 case llvm::Triple::DragonFly:
4567 case llvm::Triple::FreeBSD:
4568 case llvm::Triple::OpenBSD:
4569 case llvm::Triple::Bitrig:
4570 case llvm::Triple::Win32:
4571 return true;
4572 default:
4573 return false;
4574 }
4575}
Ulrich Weigand47445072013-05-06 16:26:41 +00004576
4577ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4578 if (RetTy->isVoidType())
4579 return ABIArgInfo::getIgnore();
4580 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4581 return ABIArgInfo::getIndirect(0);
4582 return (isPromotableIntegerType(RetTy) ?
4583 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4584}
4585
4586ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4587 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004588 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004589 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4590
4591 // Integers and enums are extended to full register width.
4592 if (isPromotableIntegerType(Ty))
4593 return ABIArgInfo::getExtend();
4594
4595 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4596 uint64_t Size = getContext().getTypeSize(Ty);
4597 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004598 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004599
4600 // Handle small structures.
4601 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4602 // Structures with flexible arrays have variable length, so really
4603 // fail the size test above.
4604 const RecordDecl *RD = RT->getDecl();
4605 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004606 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004607
4608 // The structure is passed as an unextended integer, a float, or a double.
4609 llvm::Type *PassTy;
4610 if (isFPArgumentType(Ty)) {
4611 assert(Size == 32 || Size == 64);
4612 if (Size == 32)
4613 PassTy = llvm::Type::getFloatTy(getVMContext());
4614 else
4615 PassTy = llvm::Type::getDoubleTy(getVMContext());
4616 } else
4617 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4618 return ABIArgInfo::getDirect(PassTy);
4619 }
4620
4621 // Non-structure compounds are passed indirectly.
4622 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004623 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004624
4625 return ABIArgInfo::getDirect(0);
4626}
4627
4628//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004629// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004630//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004631
4632namespace {
4633
4634class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4635public:
Chris Lattner2b037972010-07-29 02:01:43 +00004636 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4637 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004638 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4639 CodeGen::CodeGenModule &M) const;
4640};
4641
4642}
4643
4644void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4645 llvm::GlobalValue *GV,
4646 CodeGen::CodeGenModule &M) const {
4647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4648 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4649 // Handle 'interrupt' attribute:
4650 llvm::Function *F = cast<llvm::Function>(GV);
4651
4652 // Step 1: Set ISR calling convention.
4653 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4654
4655 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004656 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004657
4658 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004659 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004660 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004661 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004662 GV, &M.getModule());
4663 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004664 }
4665}
4666
Chris Lattner0cf24192010-06-28 20:05:43 +00004667//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004668// MIPS ABI Implementation. This works for both little-endian and
4669// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004670//===----------------------------------------------------------------------===//
4671
John McCall943fae92010-05-27 06:19:26 +00004672namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004673class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004674 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004675 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4676 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004677 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004678 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004679 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004680 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004681public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004682 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004683 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004684 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004685
4686 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004687 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004688 virtual void computeInfo(CGFunctionInfo &FI) const;
4689 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4690 CodeGenFunction &CGF) const;
4691};
4692
John McCall943fae92010-05-27 06:19:26 +00004693class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004694 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004695public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004696 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4697 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004698 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004699
4700 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4701 return 29;
4702 }
4703
Reed Kotler373feca2013-01-16 17:10:28 +00004704 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4705 CodeGen::CodeGenModule &CGM) const {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004706 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4707 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004708 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004709 if (FD->hasAttr<Mips16Attr>()) {
4710 Fn->addFnAttr("mips16");
4711 }
4712 else if (FD->hasAttr<NoMips16Attr>()) {
4713 Fn->addFnAttr("nomips16");
4714 }
Reed Kotler373feca2013-01-16 17:10:28 +00004715 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004716
John McCall943fae92010-05-27 06:19:26 +00004717 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004718 llvm::Value *Address) const;
John McCall3480ef22011-08-30 01:42:09 +00004719
4720 unsigned getSizeOfUnwindException() const {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004721 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004722 }
John McCall943fae92010-05-27 06:19:26 +00004723};
4724}
4725
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004726void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004727 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004728 llvm::IntegerType *IntTy =
4729 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004730
4731 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4732 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4733 ArgList.push_back(IntTy);
4734
4735 // If necessary, add one more integer type to ArgList.
4736 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4737
4738 if (R)
4739 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004740}
4741
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004742// In N32/64, an aligned double precision floating point field is passed in
4743// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004744llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004745 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4746
4747 if (IsO32) {
4748 CoerceToIntArgs(TySize, ArgList);
4749 return llvm::StructType::get(getVMContext(), ArgList);
4750 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004751
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004752 if (Ty->isComplexType())
4753 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004754
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004755 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004756
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004757 // Unions/vectors are passed in integer registers.
4758 if (!RT || !RT->isStructureOrClassType()) {
4759 CoerceToIntArgs(TySize, ArgList);
4760 return llvm::StructType::get(getVMContext(), ArgList);
4761 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004762
4763 const RecordDecl *RD = RT->getDecl();
4764 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004765 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004766
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004767 uint64_t LastOffset = 0;
4768 unsigned idx = 0;
4769 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4770
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004771 // Iterate over fields in the struct/class and check if there are any aligned
4772 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004773 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4774 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004775 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004776 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4777
4778 if (!BT || BT->getKind() != BuiltinType::Double)
4779 continue;
4780
4781 uint64_t Offset = Layout.getFieldOffset(idx);
4782 if (Offset % 64) // Ignore doubles that are not aligned.
4783 continue;
4784
4785 // Add ((Offset - LastOffset) / 64) args of type i64.
4786 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4787 ArgList.push_back(I64);
4788
4789 // Add double type.
4790 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4791 LastOffset = Offset + 64;
4792 }
4793
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004794 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4795 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004796
4797 return llvm::StructType::get(getVMContext(), ArgList);
4798}
4799
Akira Hatanakaddd66342013-10-29 18:41:15 +00004800llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4801 uint64_t Offset) const {
4802 if (OrigOffset + MinABIStackAlignInBytes > Offset)
4803 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004804
Akira Hatanakaddd66342013-10-29 18:41:15 +00004805 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004806}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00004807
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004808ABIArgInfo
4809MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00004810 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004811 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004812 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004813
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004814 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4815 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00004816 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4817 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004818
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004819 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004820 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004821 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004822 return ABIArgInfo::getIgnore();
4823
Mark Lacey3825e832013-10-06 01:33:34 +00004824 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004825 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004826 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004827 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00004828
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004829 // If we have reached here, aggregates are passed directly by coercing to
4830 // another structure type. Padding is inserted if the offset of the
4831 // aggregate is unaligned.
4832 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00004833 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004834 }
4835
4836 // Treat an enum type as its underlying type.
4837 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4838 Ty = EnumTy->getDecl()->getIntegerType();
4839
Akira Hatanaka1632af62012-01-09 19:31:25 +00004840 if (Ty->isPromotableIntegerType())
4841 return ABIArgInfo::getExtend();
4842
Akira Hatanakaddd66342013-10-29 18:41:15 +00004843 return ABIArgInfo::getDirect(
4844 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004845}
4846
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004847llvm::Type*
4848MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00004849 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004850 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004851
Akira Hatanakab6f74432012-02-09 18:49:26 +00004852 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004853 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00004854 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4855 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004856
Akira Hatanakab6f74432012-02-09 18:49:26 +00004857 // N32/64 returns struct/classes in floating point registers if the
4858 // following conditions are met:
4859 // 1. The size of the struct/class is no larger than 128-bit.
4860 // 2. The struct/class has one or two fields all of which are floating
4861 // point types.
4862 // 3. The offset of the first field is zero (this follows what gcc does).
4863 //
4864 // Any other composite results are returned in integer registers.
4865 //
4866 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4867 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4868 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004869 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004870
Akira Hatanakab6f74432012-02-09 18:49:26 +00004871 if (!BT || !BT->isFloatingPoint())
4872 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004873
David Blaikie2d7c57e2012-04-30 02:36:29 +00004874 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00004875 }
4876
4877 if (b == e)
4878 return llvm::StructType::get(getVMContext(), RTList,
4879 RD->hasAttr<PackedAttr>());
4880
4881 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004882 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004883 }
4884
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004885 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004886 return llvm::StructType::get(getVMContext(), RTList);
4887}
4888
Akira Hatanakab579fe52011-06-02 00:09:17 +00004889ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00004890 uint64_t Size = getContext().getTypeSize(RetTy);
4891
4892 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004893 return ABIArgInfo::getIgnore();
4894
Akira Hatanakac37eddf2012-05-11 21:01:17 +00004895 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00004896 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004897 return ABIArgInfo::getIndirect(0);
4898
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004899 if (Size <= 128) {
4900 if (RetTy->isAnyComplexType())
4901 return ABIArgInfo::getDirect();
4902
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004903 // O32 returns integer vectors in registers.
4904 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4905 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4906
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004907 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004908 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4909 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00004910
4911 return ABIArgInfo::getIndirect(0);
4912 }
4913
4914 // Treat an enum type as its underlying type.
4915 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4916 RetTy = EnumTy->getDecl()->getIntegerType();
4917
4918 return (RetTy->isPromotableIntegerType() ?
4919 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4920}
4921
4922void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00004923 ABIArgInfo &RetInfo = FI.getReturnInfo();
4924 RetInfo = classifyReturnType(FI.getReturnType());
4925
4926 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004927 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00004928
Akira Hatanakab579fe52011-06-02 00:09:17 +00004929 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4930 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004931 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00004932}
4933
4934llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4935 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004936 llvm::Type *BP = CGF.Int8PtrTy;
4937 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004938
4939 CGBuilderTy &Builder = CGF.Builder;
4940 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4941 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00004942 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004943 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4944 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00004945 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00004946 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004947
4948 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00004949 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4950 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4951 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4952 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004953 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4954 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4955 }
4956 else
4957 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4958
4959 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00004960 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004961 uint64_t Offset =
4962 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4963 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00004964 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004965 "ap.next");
4966 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4967
4968 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004969}
4970
John McCall943fae92010-05-27 06:19:26 +00004971bool
4972MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4973 llvm::Value *Address) const {
4974 // This information comes from gcc's implementation, which seems to
4975 // as canonical as it gets.
4976
John McCall943fae92010-05-27 06:19:26 +00004977 // Everything on MIPS is 4 bytes. Double-precision FP registers
4978 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004979 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00004980
4981 // 0-31 are the general purpose registers, $0 - $31.
4982 // 32-63 are the floating-point registers, $f0 - $f31.
4983 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4984 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00004985 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00004986
4987 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4988 // They are one bit wide and ignored here.
4989
4990 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4991 // (coprocessor 1 is the FP unit)
4992 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4993 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4994 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004995 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00004996 return false;
4997}
4998
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004999//===----------------------------------------------------------------------===//
5000// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5001// Currently subclassed only to implement custom OpenCL C function attribute
5002// handling.
5003//===----------------------------------------------------------------------===//
5004
5005namespace {
5006
5007class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5008public:
5009 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5010 : DefaultTargetCodeGenInfo(CGT) {}
5011
5012 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5013 CodeGen::CodeGenModule &M) const;
5014};
5015
5016void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5017 llvm::GlobalValue *GV,
5018 CodeGen::CodeGenModule &M) const {
5019 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5020 if (!FD) return;
5021
5022 llvm::Function *F = cast<llvm::Function>(GV);
5023
David Blaikiebbafb8a2012-03-11 07:00:24 +00005024 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005025 if (FD->hasAttr<OpenCLKernelAttr>()) {
5026 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005027 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005028 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5029 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005030 // Convert the reqd_work_group_size() attributes to metadata.
5031 llvm::LLVMContext &Context = F->getContext();
5032 llvm::NamedMDNode *OpenCLMetadata =
5033 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5034
5035 SmallVector<llvm::Value*, 5> Operands;
5036 Operands.push_back(F);
5037
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->getXDim())));
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->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005042 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005043 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005044
5045 // Add a boolean constant operand for "required" (true) or "hint" (false)
5046 // for implementing the work_group_size_hint attr later. Currently
5047 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005048 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005049 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5050 }
5051 }
5052 }
5053}
5054
5055}
John McCall943fae92010-05-27 06:19:26 +00005056
Tony Linthicum76329bf2011-12-12 21:14:55 +00005057//===----------------------------------------------------------------------===//
5058// Hexagon ABI Implementation
5059//===----------------------------------------------------------------------===//
5060
5061namespace {
5062
5063class HexagonABIInfo : public ABIInfo {
5064
5065
5066public:
5067 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5068
5069private:
5070
5071 ABIArgInfo classifyReturnType(QualType RetTy) const;
5072 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5073
5074 virtual void computeInfo(CGFunctionInfo &FI) const;
5075
5076 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5077 CodeGenFunction &CGF) const;
5078};
5079
5080class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5081public:
5082 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5083 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5084
5085 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5086 return 29;
5087 }
5088};
5089
5090}
5091
5092void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5093 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5094 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5095 it != ie; ++it)
5096 it->info = classifyArgumentType(it->type);
5097}
5098
5099ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5100 if (!isAggregateTypeForABI(Ty)) {
5101 // Treat an enum type as its underlying type.
5102 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5103 Ty = EnumTy->getDecl()->getIntegerType();
5104
5105 return (Ty->isPromotableIntegerType() ?
5106 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5107 }
5108
5109 // Ignore empty records.
5110 if (isEmptyRecord(getContext(), Ty, true))
5111 return ABIArgInfo::getIgnore();
5112
Mark Lacey3825e832013-10-06 01:33:34 +00005113 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005114 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005115
5116 uint64_t Size = getContext().getTypeSize(Ty);
5117 if (Size > 64)
5118 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5119 // Pass in the smallest viable integer type.
5120 else if (Size > 32)
5121 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5122 else if (Size > 16)
5123 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5124 else if (Size > 8)
5125 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5126 else
5127 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5128}
5129
5130ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5131 if (RetTy->isVoidType())
5132 return ABIArgInfo::getIgnore();
5133
5134 // Large vector types should be returned via memory.
5135 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5136 return ABIArgInfo::getIndirect(0);
5137
5138 if (!isAggregateTypeForABI(RetTy)) {
5139 // Treat an enum type as its underlying type.
5140 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5141 RetTy = EnumTy->getDecl()->getIntegerType();
5142
5143 return (RetTy->isPromotableIntegerType() ?
5144 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5145 }
5146
5147 // Structures with either a non-trivial destructor or a non-trivial
5148 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005149 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005150 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5151
5152 if (isEmptyRecord(getContext(), RetTy, true))
5153 return ABIArgInfo::getIgnore();
5154
5155 // Aggregates <= 8 bytes are returned in r0; other aggregates
5156 // are returned indirectly.
5157 uint64_t Size = getContext().getTypeSize(RetTy);
5158 if (Size <= 64) {
5159 // Return in the smallest viable integer type.
5160 if (Size <= 8)
5161 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5162 if (Size <= 16)
5163 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5164 if (Size <= 32)
5165 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5166 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5167 }
5168
5169 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5170}
5171
5172llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005173 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005174 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005175 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005176
5177 CGBuilderTy &Builder = CGF.Builder;
5178 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5179 "ap");
5180 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5181 llvm::Type *PTy =
5182 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5183 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5184
5185 uint64_t Offset =
5186 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5187 llvm::Value *NextAddr =
5188 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5189 "ap.next");
5190 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5191
5192 return AddrTyped;
5193}
5194
5195
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005196//===----------------------------------------------------------------------===//
5197// SPARC v9 ABI Implementation.
5198// Based on the SPARC Compliance Definition version 2.4.1.
5199//
5200// Function arguments a mapped to a nominal "parameter array" and promoted to
5201// registers depending on their type. Each argument occupies 8 or 16 bytes in
5202// the array, structs larger than 16 bytes are passed indirectly.
5203//
5204// One case requires special care:
5205//
5206// struct mixed {
5207// int i;
5208// float f;
5209// };
5210//
5211// When a struct mixed is passed by value, it only occupies 8 bytes in the
5212// parameter array, but the int is passed in an integer register, and the float
5213// is passed in a floating point register. This is represented as two arguments
5214// with the LLVM IR inreg attribute:
5215//
5216// declare void f(i32 inreg %i, float inreg %f)
5217//
5218// The code generator will only allocate 4 bytes from the parameter array for
5219// the inreg arguments. All other arguments are allocated a multiple of 8
5220// bytes.
5221//
5222namespace {
5223class SparcV9ABIInfo : public ABIInfo {
5224public:
5225 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5226
5227private:
5228 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5229 virtual void computeInfo(CGFunctionInfo &FI) const;
5230 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5231 CodeGenFunction &CGF) const;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005232
5233 // Coercion type builder for structs passed in registers. The coercion type
5234 // serves two purposes:
5235 //
5236 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5237 // in registers.
5238 // 2. Expose aligned floating point elements as first-level elements, so the
5239 // code generator knows to pass them in floating point registers.
5240 //
5241 // We also compute the InReg flag which indicates that the struct contains
5242 // aligned 32-bit floats.
5243 //
5244 struct CoerceBuilder {
5245 llvm::LLVMContext &Context;
5246 const llvm::DataLayout &DL;
5247 SmallVector<llvm::Type*, 8> Elems;
5248 uint64_t Size;
5249 bool InReg;
5250
5251 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5252 : Context(c), DL(dl), Size(0), InReg(false) {}
5253
5254 // Pad Elems with integers until Size is ToSize.
5255 void pad(uint64_t ToSize) {
5256 assert(ToSize >= Size && "Cannot remove elements");
5257 if (ToSize == Size)
5258 return;
5259
5260 // Finish the current 64-bit word.
5261 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5262 if (Aligned > Size && Aligned <= ToSize) {
5263 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5264 Size = Aligned;
5265 }
5266
5267 // Add whole 64-bit words.
5268 while (Size + 64 <= ToSize) {
5269 Elems.push_back(llvm::Type::getInt64Ty(Context));
5270 Size += 64;
5271 }
5272
5273 // Final in-word padding.
5274 if (Size < ToSize) {
5275 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5276 Size = ToSize;
5277 }
5278 }
5279
5280 // Add a floating point element at Offset.
5281 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5282 // Unaligned floats are treated as integers.
5283 if (Offset % Bits)
5284 return;
5285 // The InReg flag is only required if there are any floats < 64 bits.
5286 if (Bits < 64)
5287 InReg = true;
5288 pad(Offset);
5289 Elems.push_back(Ty);
5290 Size = Offset + Bits;
5291 }
5292
5293 // Add a struct type to the coercion type, starting at Offset (in bits).
5294 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5295 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5296 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5297 llvm::Type *ElemTy = StrTy->getElementType(i);
5298 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5299 switch (ElemTy->getTypeID()) {
5300 case llvm::Type::StructTyID:
5301 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5302 break;
5303 case llvm::Type::FloatTyID:
5304 addFloat(ElemOffset, ElemTy, 32);
5305 break;
5306 case llvm::Type::DoubleTyID:
5307 addFloat(ElemOffset, ElemTy, 64);
5308 break;
5309 case llvm::Type::FP128TyID:
5310 addFloat(ElemOffset, ElemTy, 128);
5311 break;
5312 case llvm::Type::PointerTyID:
5313 if (ElemOffset % 64 == 0) {
5314 pad(ElemOffset);
5315 Elems.push_back(ElemTy);
5316 Size += 64;
5317 }
5318 break;
5319 default:
5320 break;
5321 }
5322 }
5323 }
5324
5325 // Check if Ty is a usable substitute for the coercion type.
5326 bool isUsableType(llvm::StructType *Ty) const {
5327 if (Ty->getNumElements() != Elems.size())
5328 return false;
5329 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5330 if (Elems[i] != Ty->getElementType(i))
5331 return false;
5332 return true;
5333 }
5334
5335 // Get the coercion type as a literal struct type.
5336 llvm::Type *getType() const {
5337 if (Elems.size() == 1)
5338 return Elems.front();
5339 else
5340 return llvm::StructType::get(Context, Elems);
5341 }
5342 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005343};
5344} // end anonymous namespace
5345
5346ABIArgInfo
5347SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5348 if (Ty->isVoidType())
5349 return ABIArgInfo::getIgnore();
5350
5351 uint64_t Size = getContext().getTypeSize(Ty);
5352
5353 // Anything too big to fit in registers is passed with an explicit indirect
5354 // pointer / sret pointer.
5355 if (Size > SizeLimit)
5356 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5357
5358 // Treat an enum type as its underlying type.
5359 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5360 Ty = EnumTy->getDecl()->getIntegerType();
5361
5362 // Integer types smaller than a register are extended.
5363 if (Size < 64 && Ty->isIntegerType())
5364 return ABIArgInfo::getExtend();
5365
5366 // Other non-aggregates go in registers.
5367 if (!isAggregateTypeForABI(Ty))
5368 return ABIArgInfo::getDirect();
5369
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005370 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5371 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5372 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5373 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5374
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005375 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005376 // Build a coercion type from the LLVM struct type.
5377 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5378 if (!StrTy)
5379 return ABIArgInfo::getDirect();
5380
5381 CoerceBuilder CB(getVMContext(), getDataLayout());
5382 CB.addStruct(0, StrTy);
5383 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5384
5385 // Try to use the original type for coercion.
5386 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5387
5388 if (CB.InReg)
5389 return ABIArgInfo::getDirectInReg(CoerceTy);
5390 else
5391 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005392}
5393
5394llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5395 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005396 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5397 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5398 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5399 AI.setCoerceToType(ArgTy);
5400
5401 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5402 CGBuilderTy &Builder = CGF.Builder;
5403 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5404 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5405 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5406 llvm::Value *ArgAddr;
5407 unsigned Stride;
5408
5409 switch (AI.getKind()) {
5410 case ABIArgInfo::Expand:
5411 llvm_unreachable("Unsupported ABI kind for va_arg");
5412
5413 case ABIArgInfo::Extend:
5414 Stride = 8;
5415 ArgAddr = Builder
5416 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5417 "extend");
5418 break;
5419
5420 case ABIArgInfo::Direct:
5421 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5422 ArgAddr = Addr;
5423 break;
5424
5425 case ABIArgInfo::Indirect:
5426 Stride = 8;
5427 ArgAddr = Builder.CreateBitCast(Addr,
5428 llvm::PointerType::getUnqual(ArgPtrTy),
5429 "indirect");
5430 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5431 break;
5432
5433 case ABIArgInfo::Ignore:
5434 return llvm::UndefValue::get(ArgPtrTy);
5435 }
5436
5437 // Update VAList.
5438 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5439 Builder.CreateStore(Addr, VAListAddrAsBPP);
5440
5441 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005442}
5443
5444void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5445 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5446 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5447 it != ie; ++it)
5448 it->info = classifyType(it->type, 16 * 8);
5449}
5450
5451namespace {
5452class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5453public:
5454 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5455 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5456};
5457} // end anonymous namespace
5458
5459
Robert Lytton0e076492013-08-13 09:43:10 +00005460//===----------------------------------------------------------------------===//
5461// Xcore ABI Implementation
5462//===----------------------------------------------------------------------===//
5463namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005464class XCoreABIInfo : public DefaultABIInfo {
5465public:
5466 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5467 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5468 CodeGenFunction &CGF) const;
5469};
5470
Robert Lytton0e076492013-08-13 09:43:10 +00005471class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5472public:
5473 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005474 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005475};
Robert Lytton2d196952013-10-11 10:29:34 +00005476} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005477
Robert Lytton7d1db152013-08-19 09:46:39 +00005478llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5479 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005480 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005481
Robert Lytton2d196952013-10-11 10:29:34 +00005482 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005483 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5484 CGF.Int8PtrPtrTy);
5485 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005486
Robert Lytton2d196952013-10-11 10:29:34 +00005487 // Handle the argument.
5488 ABIArgInfo AI = classifyArgumentType(Ty);
5489 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5490 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5491 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005492 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005493 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005494 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005495 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005496 case ABIArgInfo::Expand:
5497 llvm_unreachable("Unsupported ABI kind for va_arg");
5498 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005499 Val = llvm::UndefValue::get(ArgPtrTy);
5500 ArgSize = 0;
5501 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005502 case ABIArgInfo::Extend:
5503 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005504 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5505 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5506 if (ArgSize < 4)
5507 ArgSize = 4;
5508 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005509 case ABIArgInfo::Indirect:
5510 llvm::Value *ArgAddr;
5511 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5512 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005513 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5514 ArgSize = 4;
5515 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005516 }
Robert Lytton2d196952013-10-11 10:29:34 +00005517
5518 // Increment the VAList.
5519 if (ArgSize) {
5520 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5521 Builder.CreateStore(APN, VAListAddrAsBPP);
5522 }
5523 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005524}
Robert Lytton0e076492013-08-13 09:43:10 +00005525
5526//===----------------------------------------------------------------------===//
5527// Driver code
5528//===----------------------------------------------------------------------===//
5529
Chris Lattner2b037972010-07-29 02:01:43 +00005530const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005531 if (TheTargetCodeGenInfo)
5532 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005533
John McCallc8e01702013-04-16 22:48:15 +00005534 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005535 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005536 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005537 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005538
Derek Schuff09338a22012-09-06 17:37:28 +00005539 case llvm::Triple::le32:
5540 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005541 case llvm::Triple::mips:
5542 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005543 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5544
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005545 case llvm::Triple::mips64:
5546 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005547 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5548
Tim Northover9bb857a2013-01-31 12:13:10 +00005549 case llvm::Triple::aarch64:
5550 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5551
Daniel Dunbard59655c2009-09-12 00:59:49 +00005552 case llvm::Triple::arm:
5553 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005554 {
5555 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005556 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005557 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005558 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005559 (CodeGenOpts.FloatABI != "soft" &&
5560 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005561 Kind = ARMABIInfo::AAPCS_VFP;
5562
Derek Schuffa2020962012-10-16 22:30:41 +00005563 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005564 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005565 return *(TheTargetCodeGenInfo =
5566 new NaClARMTargetCodeGenInfo(Types, Kind));
5567 default:
5568 return *(TheTargetCodeGenInfo =
5569 new ARMTargetCodeGenInfo(Types, Kind));
5570 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005571 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005572
John McCallea8d8bb2010-03-11 00:10:12 +00005573 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005574 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005575 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005576 if (Triple.isOSBinFormatELF())
5577 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5578 else
5579 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005580 case llvm::Triple::ppc64le:
5581 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5582 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005583
Peter Collingbournec947aae2012-05-20 23:28:41 +00005584 case llvm::Triple::nvptx:
5585 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005586 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005587
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005588 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005589 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005590
Ulrich Weigand47445072013-05-06 16:26:41 +00005591 case llvm::Triple::systemz:
5592 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5593
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005594 case llvm::Triple::tce:
5595 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5596
Eli Friedman33465822011-07-08 23:31:17 +00005597 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005598 bool IsDarwinVectorABI = Triple.isOSDarwin();
5599 bool IsSmallStructInRegABI =
5600 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5601 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005602
John McCall1fe2a8c2013-06-18 02:46:29 +00005603 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005604 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005605 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005606 IsDarwinVectorABI, IsSmallStructInRegABI,
5607 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005608 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005609 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005610 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005611 new X86_32TargetCodeGenInfo(Types,
5612 IsDarwinVectorABI, IsSmallStructInRegABI,
5613 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005614 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005615 }
Eli Friedman33465822011-07-08 23:31:17 +00005616 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005617
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005618 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005619 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005620
Chris Lattner04dc9572010-08-31 16:44:54 +00005621 switch (Triple.getOS()) {
5622 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005623 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005624 case llvm::Triple::Cygwin:
5625 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005626 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005627 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5628 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005629 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005630 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5631 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005632 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005633 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005634 case llvm::Triple::hexagon:
5635 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005636 case llvm::Triple::sparcv9:
5637 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005638 case llvm::Triple::xcore:
5639 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5640
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005641 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005642}