blob: bf968f34815bd6cd69c2cd9405475bbaa141efa9 [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
Reid Kleckner4982b822014-01-31 22:54:50 +0000555 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
556 bool IsInstanceMethod) const;
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 Kleckner4982b822014-01-31 22:54:50 +0000568 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State,
569 bool IsInstanceMethod) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000570 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
571 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572
Rafael Espindola75419dc2012-07-23 23:30:29 +0000573public:
574
Rafael Espindolaa6472962012-07-24 00:01:07 +0000575 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000576 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
577 CodeGenFunction &CGF) const;
578
Chad Rosier651c1832013-03-25 21:00:27 +0000579 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000580 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000581 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000582 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000583};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000584
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000585class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
586public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000587 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000588 bool d, bool p, bool w, unsigned r)
589 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000590
John McCall1fe2a8c2013-06-18 02:46:29 +0000591 static bool isStructReturnInRegABI(
592 const llvm::Triple &Triple, const CodeGenOptions &Opts);
593
Charles Davis4ea31ab2010-02-13 15:54:06 +0000594 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
595 CodeGen::CodeGenModule &CGM) const;
John McCallbeec5a02010-03-06 00:35:14 +0000596
597 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
598 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000599 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000600 return 4;
601 }
602
603 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
604 llvm::Value *Address) const;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000605
Jay Foad7c57be32011-07-11 09:56:20 +0000606 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000607 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000608 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000609 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
610 }
611
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000612 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
613 unsigned Sig = (0xeb << 0) | // jmp rel8
614 (0x06 << 8) | // .+0x08
615 ('F' << 16) |
616 ('T' << 24);
617 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
618 }
619
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000620};
621
622}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000623
624/// shouldReturnTypeInRegister - Determine if the given type should be
625/// passed in a register (for the Darwin ABI).
Reid Kleckner4982b822014-01-31 22:54:50 +0000626bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
627 bool IsInstanceMethod) const {
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,
Reid Kleckner4982b822014-01-31 22:54:50 +0000653 IsInstanceMethod);
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
Reid Kleckner4982b822014-01-31 22:54:50 +0000663 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType())
Aaron Ballman3c424412012-02-22 03:04:13 +0000664 return false;
Aaron Ballman3c424412012-02-22 03:04:13 +0000665
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000666 // Structure types are passed in register if all fields would be
667 // passed in a register.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000668 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
669 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000670 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000671
672 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000673 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000674 continue;
675
676 // Check fields recursively.
Reid Kleckner4982b822014-01-31 22:54:50 +0000677 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000678 return false;
679 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000680 return true;
681}
682
Reid Kleckner661f35b2014-01-18 01:12:41 +0000683ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
684 // If the return value is indirect, then the hidden argument is consuming one
685 // integer register.
686 if (State.FreeRegs) {
687 --State.FreeRegs;
688 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
689 }
690 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
691}
692
Reid Kleckner4982b822014-01-31 22:54:50 +0000693ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State,
694 bool IsInstanceMethod) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000695 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000696 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000697
Chris Lattner458b2aa2010-07-29 02:16:43 +0000698 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000699 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000700 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000701 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000702
703 // 128-bit vectors are a special case; they are returned in
704 // registers and we need to make sure to pick a type the LLVM
705 // backend will like.
706 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000707 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000708 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000709
710 // Always return in register if it fits in a general purpose
711 // register, or if it is 64 bits and has a single element.
712 if ((Size == 8 || Size == 16 || Size == 32) ||
713 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000714 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000715 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000716
Reid Kleckner661f35b2014-01-18 01:12:41 +0000717 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000718 }
719
720 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000721 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000722
John McCalla1dee5302010-08-22 10:59:02 +0000723 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000724 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000725 if (isRecordReturnIndirect(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000726 return getIndirectReturnResult(State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000727
Anders Carlsson5789c492009-10-20 22:07:59 +0000728 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000729 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000730 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000731 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000732
David Chisnallde3a0692009-08-17 23:08:21 +0000733 // If specified, structs and unions are always indirect.
734 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000735 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000736
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000737 // Small structures which are register sized are generally returned
738 // in a register.
Reid Kleckner4982b822014-01-31 22:54:50 +0000739 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000740 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000741
742 // As a special-case, if the struct is a "single-element" struct, and
743 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000744 // floating-point register. (MSVC does not apply this special case.)
745 // We apply a similar transformation for pointer types to improve the
746 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000747 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000748 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000749 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000750 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
751
752 // FIXME: We should be able to narrow this integer in cases with dead
753 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000754 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000755 }
756
Reid Kleckner661f35b2014-01-18 01:12:41 +0000757 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000758 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000759
Chris Lattner458b2aa2010-07-29 02:16:43 +0000760 // Treat an enum type as its underlying type.
761 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
762 RetTy = EnumTy->getDecl()->getIntegerType();
763
764 return (RetTy->isPromotableIntegerType() ?
765 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000766}
767
Eli Friedman7919bea2012-06-05 19:40:46 +0000768static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
769 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
770}
771
Daniel Dunbared23de32010-09-16 20:42:00 +0000772static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
773 const RecordType *RT = Ty->getAs<RecordType>();
774 if (!RT)
775 return 0;
776 const RecordDecl *RD = RT->getDecl();
777
778 // If this is a C++ record, check the bases first.
779 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
780 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
781 e = CXXRD->bases_end(); i != e; ++i)
782 if (!isRecordWithSSEVectorType(Context, i->getType()))
783 return false;
784
785 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
786 i != e; ++i) {
787 QualType FT = i->getType();
788
Eli Friedman7919bea2012-06-05 19:40:46 +0000789 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000790 return true;
791
792 if (isRecordWithSSEVectorType(Context, FT))
793 return true;
794 }
795
796 return false;
797}
798
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000799unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
800 unsigned Align) const {
801 // Otherwise, if the alignment is less than or equal to the minimum ABI
802 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000803 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000804 return 0; // Use default alignment.
805
806 // On non-Darwin, the stack type alignment is always 4.
807 if (!IsDarwinVectorABI) {
808 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000809 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000810 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000811
Daniel Dunbared23de32010-09-16 20:42:00 +0000812 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000813 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
814 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000815 return 16;
816
817 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000818}
819
Rafael Espindola703c47f2012-10-19 05:04:37 +0000820ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000821 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000822 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000823 if (State.FreeRegs) {
824 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000825 return ABIArgInfo::getIndirectInReg(0, false);
826 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000827 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000828 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000829
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000830 // Compute the byval alignment.
831 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
832 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
833 if (StackAlign == 0)
Chris Lattnere76b95a2011-05-22 23:35:00 +0000834 return ABIArgInfo::getIndirect(4);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000835
836 // If the stack alignment is less than the type alignment, realign the
837 // argument.
838 if (StackAlign < TypeAlign)
839 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
840 /*Realign=*/true);
841
842 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000843}
844
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000845X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
846 const Type *T = isSingleElementStruct(Ty, getContext());
847 if (!T)
848 T = Ty.getTypePtr();
849
850 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
851 BuiltinType::Kind K = BT->getKind();
852 if (K == BuiltinType::Float || K == BuiltinType::Double)
853 return Float;
854 }
855 return Integer;
856}
857
Reid Kleckner661f35b2014-01-18 01:12:41 +0000858bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
859 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000860 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000861 Class C = classify(Ty);
862 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000863 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000864
Rafael Espindola077dd592012-10-24 01:58:58 +0000865 unsigned Size = getContext().getTypeSize(Ty);
866 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000867
868 if (SizeInRegs == 0)
869 return false;
870
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871 if (SizeInRegs > State.FreeRegs) {
872 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000873 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000874 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000875
Reid Kleckner661f35b2014-01-18 01:12:41 +0000876 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000877
Reid Kleckner661f35b2014-01-18 01:12:41 +0000878 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000879 if (Size > 32)
880 return false;
881
882 if (Ty->isIntegralOrEnumerationType())
883 return true;
884
885 if (Ty->isPointerType())
886 return true;
887
888 if (Ty->isReferenceType())
889 return true;
890
Reid Kleckner661f35b2014-01-18 01:12:41 +0000891 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000892 NeedsPadding = true;
893
Rafael Espindola077dd592012-10-24 01:58:58 +0000894 return false;
895 }
896
Rafael Espindola703c47f2012-10-19 05:04:37 +0000897 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000898}
899
Reid Kleckner661f35b2014-01-18 01:12:41 +0000900ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000901 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000902 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000903 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000904 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000905 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000906
Mark Lacey3825e832013-10-06 01:33:34 +0000907 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000908 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory,
909 State);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000910
911 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000912 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000913 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000914 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000915
Eli Friedman9f061a32011-11-18 00:28:11 +0000916 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000917 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000918 return ABIArgInfo::getIgnore();
919
Rafael Espindolafad28de2012-10-24 01:59:00 +0000920 llvm::LLVMContext &LLVMContext = getVMContext();
921 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
922 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000923 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000924 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000925 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000926 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
927 return ABIArgInfo::getDirectInReg(Result);
928 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000929 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000930
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000931 // Expand small (<= 128-bit) record types when we know that the stack layout
932 // of those arguments will match the struct. This is important because the
933 // LLVM backend isn't smart enough to remove byval, which inhibits many
934 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000935 if (getContext().getTypeSize(Ty) <= 4*32 &&
936 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000937 return ABIArgInfo::getExpandWithPadding(
938 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000939
Reid Kleckner661f35b2014-01-18 01:12:41 +0000940 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000941 }
942
Chris Lattnerd774ae92010-08-26 20:05:13 +0000943 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000944 // On Darwin, some vectors are passed in memory, we handle this by passing
945 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000946 if (IsDarwinVectorABI) {
947 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000948 if ((Size == 8 || Size == 16 || Size == 32) ||
949 (Size == 64 && VT->getNumElements() == 1))
950 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
951 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000952 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000953
Chad Rosier651c1832013-03-25 21:00:27 +0000954 if (IsX86_MMXType(CGT.ConvertType(Ty)))
955 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000956
Chris Lattnerd774ae92010-08-26 20:05:13 +0000957 return ABIArgInfo::getDirect();
958 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000959
960
Chris Lattner458b2aa2010-07-29 02:16:43 +0000961 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
962 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000963
Rafael Espindolafad28de2012-10-24 01:59:00 +0000964 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000965 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000966
967 if (Ty->isPromotableIntegerType()) {
968 if (InReg)
969 return ABIArgInfo::getExtendInReg();
970 return ABIArgInfo::getExtend();
971 }
972 if (InReg)
973 return ABIArgInfo::getDirectInReg();
974 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000975}
976
Rafael Espindolaa6472962012-07-24 00:01:07 +0000977void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000978 CCState State(FI.getCallingConvention());
979 if (State.CC == llvm::CallingConv::X86_FastCall)
980 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000981 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000982 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +0000983 else
Reid Kleckner661f35b2014-01-18 01:12:41 +0000984 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000985
Reid Kleckner4982b822014-01-31 22:54:50 +0000986 FI.getReturnInfo() =
987 classifyReturnType(FI.getReturnType(), State, FI.isInstanceMethod());
988
989 // On win32, use the x86_cdeclmethodcc convention for cdecl methods that use
990 // sret. This convention swaps the order of the first two parameters behind
991 // the scenes to match MSVC.
992 if (IsWin32StructABI && FI.isInstanceMethod() &&
993 FI.getCallingConvention() == llvm::CallingConv::C &&
994 FI.getReturnInfo().isIndirect())
995 FI.setEffectiveCallingConvention(llvm::CallingConv::X86_CDeclMethod);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000996
Rafael Espindolaa6472962012-07-24 00:01:07 +0000997 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
998 it != ie; ++it)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000999 it->info = classifyArgumentType(it->type, State);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001000}
1001
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001002llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1003 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001004 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001005
1006 CGBuilderTy &Builder = CGF.Builder;
1007 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1008 "ap");
1009 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001010
1011 // Compute if the address needs to be aligned
1012 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1013 Align = getTypeStackAlignInBytes(Ty, Align);
1014 Align = std::max(Align, 4U);
1015 if (Align > 4) {
1016 // addr = (addr + align - 1) & -align;
1017 llvm::Value *Offset =
1018 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1019 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1020 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1021 CGF.Int32Ty);
1022 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1023 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1024 Addr->getType(),
1025 "ap.cur.aligned");
1026 }
1027
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001028 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001029 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001030 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1031
1032 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001033 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001034 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001035 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001036 "ap.next");
1037 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1038
1039 return AddrTyped;
1040}
1041
Charles Davis4ea31ab2010-02-13 15:54:06 +00001042void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1043 llvm::GlobalValue *GV,
1044 CodeGen::CodeGenModule &CGM) const {
1045 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1046 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1047 // Get the LLVM function.
1048 llvm::Function *Fn = cast<llvm::Function>(GV);
1049
1050 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001051 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001052 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001053 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1054 llvm::AttributeSet::get(CGM.getLLVMContext(),
1055 llvm::AttributeSet::FunctionIndex,
1056 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001057 }
1058 }
1059}
1060
John McCallbeec5a02010-03-06 00:35:14 +00001061bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1062 CodeGen::CodeGenFunction &CGF,
1063 llvm::Value *Address) const {
1064 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001065
Chris Lattnerece04092012-02-07 00:39:47 +00001066 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001067
John McCallbeec5a02010-03-06 00:35:14 +00001068 // 0-7 are the eight integer registers; the order is different
1069 // on Darwin (for EH), but the range is the same.
1070 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001071 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001072
John McCallc8e01702013-04-16 22:48:15 +00001073 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001074 // 12-16 are st(0..4). Not sure why we stop at 4.
1075 // These have size 16, which is sizeof(long double) on
1076 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001077 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001078 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001079
John McCallbeec5a02010-03-06 00:35:14 +00001080 } else {
1081 // 9 is %eflags, which doesn't get a size on Darwin for some
1082 // reason.
1083 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1084
1085 // 11-16 are st(0..5). Not sure why we stop at 5.
1086 // These have size 12, which is sizeof(long double) on
1087 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001088 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001089 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1090 }
John McCallbeec5a02010-03-06 00:35:14 +00001091
1092 return false;
1093}
1094
Chris Lattner0cf24192010-06-28 20:05:43 +00001095//===----------------------------------------------------------------------===//
1096// X86-64 ABI Implementation
1097//===----------------------------------------------------------------------===//
1098
1099
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001100namespace {
1101/// X86_64ABIInfo - The X86_64 ABI information.
1102class X86_64ABIInfo : public ABIInfo {
1103 enum Class {
1104 Integer = 0,
1105 SSE,
1106 SSEUp,
1107 X87,
1108 X87Up,
1109 ComplexX87,
1110 NoClass,
1111 Memory
1112 };
1113
1114 /// merge - Implement the X86_64 ABI merging algorithm.
1115 ///
1116 /// Merge an accumulating classification \arg Accum with a field
1117 /// classification \arg Field.
1118 ///
1119 /// \param Accum - The accumulating classification. This should
1120 /// always be either NoClass or the result of a previous merge
1121 /// call. In addition, this should never be Memory (the caller
1122 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001123 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001124
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001125 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1126 ///
1127 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1128 /// final MEMORY or SSE classes when necessary.
1129 ///
1130 /// \param AggregateSize - The size of the current aggregate in
1131 /// the classification process.
1132 ///
1133 /// \param Lo - The classification for the parts of the type
1134 /// residing in the low word of the containing object.
1135 ///
1136 /// \param Hi - The classification for the parts of the type
1137 /// residing in the higher words of the containing object.
1138 ///
1139 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1140
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001141 /// classify - Determine the x86_64 register classes in which the
1142 /// given type T should be passed.
1143 ///
1144 /// \param Lo - The classification for the parts of the type
1145 /// residing in the low word of the containing object.
1146 ///
1147 /// \param Hi - The classification for the parts of the type
1148 /// residing in the high word of the containing object.
1149 ///
1150 /// \param OffsetBase - The bit offset of this type in the
1151 /// containing object. Some parameters are classified different
1152 /// depending on whether they straddle an eightbyte boundary.
1153 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001154 /// \param isNamedArg - Whether the argument in question is a "named"
1155 /// argument, as used in AMD64-ABI 3.5.7.
1156 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001157 /// If a word is unused its result will be NoClass; if a type should
1158 /// be passed in Memory then at least the classification of \arg Lo
1159 /// will be Memory.
1160 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001161 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001162 ///
1163 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1164 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001165 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1166 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001167
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001168 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001169 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1170 unsigned IROffset, QualType SourceTy,
1171 unsigned SourceOffset) const;
1172 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1173 unsigned IROffset, QualType SourceTy,
1174 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001175
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001176 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001177 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001178 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001179
1180 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001182 ///
1183 /// \param freeIntRegs - The number of free integer registers remaining
1184 /// available.
1185 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001186
Chris Lattner458b2aa2010-07-29 02:16:43 +00001187 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001188
Bill Wendling5cd41c42010-10-18 03:41:31 +00001189 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001190 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001191 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001192 unsigned &neededSSE,
1193 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001194
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001195 bool IsIllegalVectorType(QualType Ty) const;
1196
John McCalle0fda732011-04-21 01:20:55 +00001197 /// The 0.98 ABI revision clarified a lot of ambiguities,
1198 /// unfortunately in ways that were not always consistent with
1199 /// certain previous compilers. In particular, platforms which
1200 /// required strict binary compatibility with older versions of GCC
1201 /// may need to exempt themselves.
1202 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001203 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001204 }
1205
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001206 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001207 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1208 // 64-bit hardware.
1209 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001210
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001211public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001212 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001213 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001214 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001215 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001216
John McCalla729c622012-02-17 03:33:10 +00001217 bool isPassedUsingAVXType(QualType type) const {
1218 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001219 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001220 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1221 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001222 if (info.isDirect()) {
1223 llvm::Type *ty = info.getCoerceToType();
1224 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1225 return (vectorTy->getBitWidth() > 128);
1226 }
1227 return false;
1228 }
1229
Chris Lattner22326a12010-07-29 02:31:05 +00001230 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001231
1232 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1233 CodeGenFunction &CGF) const;
1234};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001235
Chris Lattner04dc9572010-08-31 16:44:54 +00001236/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001237class WinX86_64ABIInfo : public ABIInfo {
1238
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001239 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001240
Chris Lattner04dc9572010-08-31 16:44:54 +00001241public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001242 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1243
1244 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattner04dc9572010-08-31 16:44:54 +00001245
1246 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1247 CodeGenFunction &CGF) const;
1248};
1249
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001250class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1251public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001252 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001253 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001254
John McCalla729c622012-02-17 03:33:10 +00001255 const X86_64ABIInfo &getABIInfo() const {
1256 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1257 }
1258
John McCallbeec5a02010-03-06 00:35:14 +00001259 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1260 return 7;
1261 }
1262
1263 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1264 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001265 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001266
John McCall943fae92010-05-27 06:19:26 +00001267 // 0-15 are the 16 integer registers.
1268 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001269 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001270 return false;
1271 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001272
Jay Foad7c57be32011-07-11 09:56:20 +00001273 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001274 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +00001275 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001276 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1277 }
1278
John McCalla729c622012-02-17 03:33:10 +00001279 bool isNoProtoCallVariadic(const CallArgList &args,
1280 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +00001281 // The default CC on x86-64 sets %al to the number of SSA
1282 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001283 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001284 // that when AVX types are involved: the ABI explicitly states it is
1285 // undefined, and it doesn't work in practice because of how the ABI
1286 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001287 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001288 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001289 for (CallArgList::const_iterator
1290 it = args.begin(), ie = args.end(); it != ie; ++it) {
1291 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1292 HasAVXType = true;
1293 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001294 }
1295 }
John McCalla729c622012-02-17 03:33:10 +00001296
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001297 if (!HasAVXType)
1298 return true;
1299 }
John McCallcbc038a2011-09-21 08:08:30 +00001300
John McCalla729c622012-02-17 03:33:10 +00001301 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001302 }
1303
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001304 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
1305 unsigned Sig = (0xeb << 0) | // jmp rel8
1306 (0x0a << 8) | // .+0x0c
1307 ('F' << 16) |
1308 ('T' << 24);
1309 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1310 }
1311
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001312};
1313
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001314static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1315 // If the argument does not end in .lib, automatically add the suffix. This
1316 // matches the behavior of MSVC.
1317 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001318 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001319 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001320 return ArgStr;
1321}
1322
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001323class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1324public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001325 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1326 bool d, bool p, bool w, unsigned RegParms)
1327 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001328
1329 void getDependentLibraryOption(llvm::StringRef Lib,
1330 llvm::SmallString<24> &Opt) const {
1331 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001332 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001333 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001334
1335 void getDetectMismatchOption(llvm::StringRef Name,
1336 llvm::StringRef Value,
1337 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001338 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001339 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001340};
1341
Chris Lattner04dc9572010-08-31 16:44:54 +00001342class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1343public:
1344 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1345 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1346
1347 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1348 return 7;
1349 }
1350
1351 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1352 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001353 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001354
Chris Lattner04dc9572010-08-31 16:44:54 +00001355 // 0-15 are the 16 integer registers.
1356 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001357 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001358 return false;
1359 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001360
1361 void getDependentLibraryOption(llvm::StringRef Lib,
1362 llvm::SmallString<24> &Opt) const {
1363 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001364 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001365 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001366
1367 void getDetectMismatchOption(llvm::StringRef Name,
1368 llvm::StringRef Value,
1369 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001370 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001371 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001372};
1373
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001374}
1375
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001376void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1377 Class &Hi) const {
1378 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1379 //
1380 // (a) If one of the classes is Memory, the whole argument is passed in
1381 // memory.
1382 //
1383 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1384 // memory.
1385 //
1386 // (c) If the size of the aggregate exceeds two eightbytes and the first
1387 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1388 // argument is passed in memory. NOTE: This is necessary to keep the
1389 // ABI working for processors that don't support the __m256 type.
1390 //
1391 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1392 //
1393 // Some of these are enforced by the merging logic. Others can arise
1394 // only with unions; for example:
1395 // union { _Complex double; unsigned; }
1396 //
1397 // Note that clauses (b) and (c) were added in 0.98.
1398 //
1399 if (Hi == Memory)
1400 Lo = Memory;
1401 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1402 Lo = Memory;
1403 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1404 Lo = Memory;
1405 if (Hi == SSEUp && Lo != SSE)
1406 Hi = SSE;
1407}
1408
Chris Lattnerd776fb12010-06-28 21:43:59 +00001409X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001410 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1411 // classified recursively so that always two fields are
1412 // considered. The resulting class is calculated according to
1413 // the classes of the fields in the eightbyte:
1414 //
1415 // (a) If both classes are equal, this is the resulting class.
1416 //
1417 // (b) If one of the classes is NO_CLASS, the resulting class is
1418 // the other class.
1419 //
1420 // (c) If one of the classes is MEMORY, the result is the MEMORY
1421 // class.
1422 //
1423 // (d) If one of the classes is INTEGER, the result is the
1424 // INTEGER.
1425 //
1426 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1427 // MEMORY is used as class.
1428 //
1429 // (f) Otherwise class SSE is used.
1430
1431 // Accum should never be memory (we should have returned) or
1432 // ComplexX87 (because this cannot be passed in a structure).
1433 assert((Accum != Memory && Accum != ComplexX87) &&
1434 "Invalid accumulated classification during merge.");
1435 if (Accum == Field || Field == NoClass)
1436 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001437 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001438 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001439 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001440 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001441 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001442 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001443 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1444 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001445 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001446 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001447}
1448
Chris Lattner5c740f12010-06-30 19:14:05 +00001449void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001450 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001451 // FIXME: This code can be simplified by introducing a simple value class for
1452 // Class pairs with appropriate constructor methods for the various
1453 // situations.
1454
1455 // FIXME: Some of the split computations are wrong; unaligned vectors
1456 // shouldn't be passed in registers for example, so there is no chance they
1457 // can straddle an eightbyte. Verify & simplify.
1458
1459 Lo = Hi = NoClass;
1460
1461 Class &Current = OffsetBase < 64 ? Lo : Hi;
1462 Current = Memory;
1463
John McCall9dd450b2009-09-21 23:43:11 +00001464 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001465 BuiltinType::Kind k = BT->getKind();
1466
1467 if (k == BuiltinType::Void) {
1468 Current = NoClass;
1469 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1470 Lo = Integer;
1471 Hi = Integer;
1472 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1473 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001474 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1475 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001476 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001477 Current = SSE;
1478 } else if (k == BuiltinType::LongDouble) {
1479 Lo = X87;
1480 Hi = X87Up;
1481 }
1482 // FIXME: _Decimal32 and _Decimal64 are SSE.
1483 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001484 return;
1485 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001486
Chris Lattnerd776fb12010-06-28 21:43:59 +00001487 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001488 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001489 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
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->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001494 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001495 return;
1496 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001497
Chris Lattnerd776fb12010-06-28 21:43:59 +00001498 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001499 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001500 Lo = Hi = Integer;
1501 else
1502 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001503 return;
1504 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001505
Chris Lattnerd776fb12010-06-28 21:43:59 +00001506 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001507 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001508 if (Size == 32) {
1509 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1510 // float> as integer.
1511 Current = Integer;
1512
1513 // If this type crosses an eightbyte boundary, it should be
1514 // split.
1515 uint64_t EB_Real = (OffsetBase) / 64;
1516 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1517 if (EB_Real != EB_Imag)
1518 Hi = Lo;
1519 } else if (Size == 64) {
1520 // gcc passes <1 x double> in memory. :(
1521 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1522 return;
1523
1524 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001525 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001526 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1527 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1528 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001529 Current = Integer;
1530 else
1531 Current = SSE;
1532
1533 // If this type crosses an eightbyte boundary, it should be
1534 // split.
1535 if (OffsetBase && OffsetBase != 64)
1536 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001537 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001538 // Arguments of 256-bits are split into four eightbyte chunks. The
1539 // least significant one belongs to class SSE and all the others to class
1540 // SSEUP. The original Lo and Hi design considers that types can't be
1541 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1542 // This design isn't correct for 256-bits, but since there're no cases
1543 // where the upper parts would need to be inspected, avoid adding
1544 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001545 //
1546 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1547 // registers if they are "named", i.e. not part of the "..." of a
1548 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001549 Lo = SSE;
1550 Hi = SSEUp;
1551 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001552 return;
1553 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001554
Chris Lattnerd776fb12010-06-28 21:43:59 +00001555 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001556 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001557
Chris Lattner2b037972010-07-29 02:01:43 +00001558 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001559 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001560 if (Size <= 64)
1561 Current = Integer;
1562 else if (Size <= 128)
1563 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001564 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001565 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001566 else if (ET == getContext().DoubleTy ||
1567 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001568 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001569 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001570 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001571 Current = ComplexX87;
1572
1573 // If this complex type crosses an eightbyte boundary then it
1574 // should be split.
1575 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001576 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001577 if (Hi == NoClass && EB_Real != EB_Imag)
1578 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001579
Chris Lattnerd776fb12010-06-28 21:43:59 +00001580 return;
1581 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001582
Chris Lattner2b037972010-07-29 02:01:43 +00001583 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001584 // Arrays are treated like structures.
1585
Chris Lattner2b037972010-07-29 02:01:43 +00001586 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001587
1588 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001589 // than four eightbytes, ..., it has class MEMORY.
1590 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001591 return;
1592
1593 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1594 // fields, it has class MEMORY.
1595 //
1596 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001597 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001598 return;
1599
1600 // Otherwise implement simplified merge. We could be smarter about
1601 // this, but it isn't worth it and would be harder to verify.
1602 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001603 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001604 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001605
1606 // The only case a 256-bit wide vector could be used is when the array
1607 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1608 // to work for sizes wider than 128, early check and fallback to memory.
1609 if (Size > 128 && EltSize != 256)
1610 return;
1611
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001612 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1613 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001614 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001615 Lo = merge(Lo, FieldLo);
1616 Hi = merge(Hi, FieldHi);
1617 if (Lo == Memory || Hi == Memory)
1618 break;
1619 }
1620
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001621 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001622 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001623 return;
1624 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001625
Chris Lattnerd776fb12010-06-28 21:43:59 +00001626 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001627 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001628
1629 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001630 // than four eightbytes, ..., it has class MEMORY.
1631 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001632 return;
1633
Anders Carlsson20759ad2009-09-16 15:53:40 +00001634 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1635 // copy constructor or a non-trivial destructor, it is passed by invisible
1636 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001637 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001638 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001639
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001640 const RecordDecl *RD = RT->getDecl();
1641
1642 // Assume variable sized types are passed in memory.
1643 if (RD->hasFlexibleArrayMember())
1644 return;
1645
Chris Lattner2b037972010-07-29 02:01:43 +00001646 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001647
1648 // Reset Lo class, this will be recomputed.
1649 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001650
1651 // If this is a C++ record, classify the bases first.
1652 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1653 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1654 e = CXXRD->bases_end(); i != e; ++i) {
1655 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1656 "Unexpected base class!");
1657 const CXXRecordDecl *Base =
1658 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1659
1660 // Classify this field.
1661 //
1662 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1663 // single eightbyte, each is classified separately. Each eightbyte gets
1664 // initialized to class NO_CLASS.
1665 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001666 uint64_t Offset =
1667 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman96fd2642013-06-12 00:13:45 +00001668 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001669 Lo = merge(Lo, FieldLo);
1670 Hi = merge(Hi, FieldHi);
1671 if (Lo == Memory || Hi == Memory)
1672 break;
1673 }
1674 }
1675
1676 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001677 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001678 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001679 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001680 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1681 bool BitField = i->isBitField();
1682
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001683 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1684 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001685 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001686 // The only case a 256-bit wide vector could be used is when the struct
1687 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1688 // to work for sizes wider than 128, early check and fallback to memory.
1689 //
1690 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1691 Lo = Memory;
1692 return;
1693 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001694 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001695 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001696 Lo = Memory;
1697 return;
1698 }
1699
1700 // Classify this field.
1701 //
1702 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1703 // exceeds a single eightbyte, each is classified
1704 // separately. Each eightbyte gets initialized to class
1705 // NO_CLASS.
1706 Class FieldLo, FieldHi;
1707
1708 // Bit-fields require special handling, they do not force the
1709 // structure to be passed in memory even if unaligned, and
1710 // therefore they can straddle an eightbyte.
1711 if (BitField) {
1712 // Ignore padding bit-fields.
1713 if (i->isUnnamedBitfield())
1714 continue;
1715
1716 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001717 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001718
1719 uint64_t EB_Lo = Offset / 64;
1720 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001721
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001722 if (EB_Lo) {
1723 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1724 FieldLo = NoClass;
1725 FieldHi = Integer;
1726 } else {
1727 FieldLo = Integer;
1728 FieldHi = EB_Hi ? Integer : NoClass;
1729 }
1730 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001731 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001732 Lo = merge(Lo, FieldLo);
1733 Hi = merge(Hi, FieldHi);
1734 if (Lo == Memory || Hi == Memory)
1735 break;
1736 }
1737
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001738 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001739 }
1740}
1741
Chris Lattner22a931e2010-06-29 06:01:59 +00001742ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001743 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1744 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001745 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001746 // Treat an enum type as its underlying type.
1747 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1748 Ty = EnumTy->getDecl()->getIntegerType();
1749
1750 return (Ty->isPromotableIntegerType() ?
1751 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1752 }
1753
1754 return ABIArgInfo::getIndirect(0);
1755}
1756
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001757bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1758 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1759 uint64_t Size = getContext().getTypeSize(VecTy);
1760 unsigned LargestVector = HasAVX ? 256 : 128;
1761 if (Size <= 64 || Size > LargestVector)
1762 return true;
1763 }
1764
1765 return false;
1766}
1767
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001768ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1769 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001770 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1771 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001772 //
1773 // This assumption is optimistic, as there could be free registers available
1774 // when we need to pass this argument in memory, and LLVM could try to pass
1775 // the argument in the free register. This does not seem to happen currently,
1776 // but this code would be much safer if we could mark the argument with
1777 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001778 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001779 // Treat an enum type as its underlying type.
1780 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1781 Ty = EnumTy->getDecl()->getIntegerType();
1782
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001783 return (Ty->isPromotableIntegerType() ?
1784 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001785 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001786
Mark Lacey3825e832013-10-06 01:33:34 +00001787 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001788 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001789
Chris Lattner44c2b902011-05-22 23:21:23 +00001790 // Compute the byval alignment. We specify the alignment of the byval in all
1791 // cases so that the mid-level optimizer knows the alignment of the byval.
1792 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001793
1794 // Attempt to avoid passing indirect results using byval when possible. This
1795 // is important for good codegen.
1796 //
1797 // We do this by coercing the value into a scalar type which the backend can
1798 // handle naturally (i.e., without using byval).
1799 //
1800 // For simplicity, we currently only do this when we have exhausted all of the
1801 // free integer registers. Doing this when there are free integer registers
1802 // would require more care, as we would have to ensure that the coerced value
1803 // did not claim the unused register. That would require either reording the
1804 // arguments to the function (so that any subsequent inreg values came first),
1805 // or only doing this optimization when there were no following arguments that
1806 // might be inreg.
1807 //
1808 // We currently expect it to be rare (particularly in well written code) for
1809 // arguments to be passed on the stack when there are still free integer
1810 // registers available (this would typically imply large structs being passed
1811 // by value), so this seems like a fair tradeoff for now.
1812 //
1813 // We can revisit this if the backend grows support for 'onstack' parameter
1814 // attributes. See PR12193.
1815 if (freeIntRegs == 0) {
1816 uint64_t Size = getContext().getTypeSize(Ty);
1817
1818 // If this type fits in an eightbyte, coerce it into the matching integral
1819 // type, which will end up on the stack (with alignment 8).
1820 if (Align == 8 && Size <= 64)
1821 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1822 Size));
1823 }
1824
Chris Lattner44c2b902011-05-22 23:21:23 +00001825 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001826}
1827
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001828/// GetByteVectorType - The ABI specifies that a value should be passed in an
1829/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001830/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001831llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001832 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001833
Chris Lattner9fa15c32010-07-29 05:02:29 +00001834 // Wrapper structs that just contain vectors are passed just like vectors,
1835 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001836 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001837 while (STy && STy->getNumElements() == 1) {
1838 IRType = STy->getElementType(0);
1839 STy = dyn_cast<llvm::StructType>(IRType);
1840 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001841
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001842 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001843 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1844 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001845 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001846 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001847 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1848 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1849 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1850 EltTy->isIntegerTy(128)))
1851 return VT;
1852 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001853
Chris Lattner4200fe42010-07-29 04:56:46 +00001854 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1855}
1856
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001857/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1858/// is known to either be off the end of the specified type or being in
1859/// alignment padding. The user type specified is known to be at most 128 bits
1860/// in size, and have passed through X86_64ABIInfo::classify with a successful
1861/// classification that put one of the two halves in the INTEGER class.
1862///
1863/// It is conservatively correct to return false.
1864static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1865 unsigned EndBit, ASTContext &Context) {
1866 // If the bytes being queried are off the end of the type, there is no user
1867 // data hiding here. This handles analysis of builtins, vectors and other
1868 // types that don't contain interesting padding.
1869 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1870 if (TySize <= StartBit)
1871 return true;
1872
Chris Lattner98076a22010-07-29 07:43:55 +00001873 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1874 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1875 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1876
1877 // Check each element to see if the element overlaps with the queried range.
1878 for (unsigned i = 0; i != NumElts; ++i) {
1879 // If the element is after the span we care about, then we're done..
1880 unsigned EltOffset = i*EltSize;
1881 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001882
Chris Lattner98076a22010-07-29 07:43:55 +00001883 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1884 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1885 EndBit-EltOffset, Context))
1886 return false;
1887 }
1888 // If it overlaps no elements, then it is safe to process as padding.
1889 return true;
1890 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001891
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001892 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1893 const RecordDecl *RD = RT->getDecl();
1894 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001895
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001896 // If this is a C++ record, check the bases first.
1897 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1898 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1899 e = CXXRD->bases_end(); i != e; ++i) {
1900 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1901 "Unexpected base class!");
1902 const CXXRecordDecl *Base =
1903 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001904
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001905 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001906 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001907 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001908
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001909 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1910 if (!BitsContainNoUserData(i->getType(), BaseStart,
1911 EndBit-BaseOffset, Context))
1912 return false;
1913 }
1914 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001915
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001916 // Verify that no field has data that overlaps the region of interest. Yes
1917 // this could be sped up a lot by being smarter about queried fields,
1918 // however we're only looking at structs up to 16 bytes, so we don't care
1919 // much.
1920 unsigned idx = 0;
1921 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1922 i != e; ++i, ++idx) {
1923 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001924
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001925 // If we found a field after the region we care about, then we're done.
1926 if (FieldOffset >= EndBit) break;
1927
1928 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1929 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1930 Context))
1931 return false;
1932 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001933
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001934 // If nothing in this record overlapped the area of interest, then we're
1935 // clean.
1936 return true;
1937 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001938
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001939 return false;
1940}
1941
Chris Lattnere556a712010-07-29 18:39:32 +00001942/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1943/// float member at the specified offset. For example, {int,{float}} has a
1944/// float at offset 4. It is conservatively correct for this routine to return
1945/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00001946static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001947 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00001948 // Base case if we find a float.
1949 if (IROffset == 0 && IRType->isFloatTy())
1950 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001951
Chris Lattnere556a712010-07-29 18:39:32 +00001952 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001953 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00001954 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1955 unsigned Elt = SL->getElementContainingOffset(IROffset);
1956 IROffset -= SL->getElementOffset(Elt);
1957 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1958 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001959
Chris Lattnere556a712010-07-29 18:39:32 +00001960 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001961 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1962 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00001963 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1964 IROffset -= IROffset/EltSize*EltSize;
1965 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1966 }
1967
1968 return false;
1969}
1970
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001971
1972/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1973/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001974llvm::Type *X86_64ABIInfo::
1975GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001976 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00001977 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001978 // pass as float if the last 4 bytes is just padding. This happens for
1979 // structs that contain 3 floats.
1980 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1981 SourceOffset*8+64, getContext()))
1982 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001983
Chris Lattnere556a712010-07-29 18:39:32 +00001984 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1985 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1986 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00001987 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1988 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00001989 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001990
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001991 return llvm::Type::getDoubleTy(getVMContext());
1992}
1993
1994
Chris Lattner1c56d9a2010-07-29 17:40:35 +00001995/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1996/// an 8-byte GPR. This means that we either have a scalar or we are talking
1997/// about the high or low part of an up-to-16-byte struct. This routine picks
1998/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00001999/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2000/// etc).
2001///
2002/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2003/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2004/// the 8-byte value references. PrefType may be null.
2005///
2006/// SourceTy is the source level type for the entire argument. SourceOffset is
2007/// an offset into this that we're processing (which is always either 0 or 8).
2008///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002009llvm::Type *X86_64ABIInfo::
2010GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002011 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002012 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2013 // returning an 8-byte unit starting with it. See if we can safely use it.
2014 if (IROffset == 0) {
2015 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002016 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2017 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002018 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002019
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002020 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2021 // goodness in the source type is just tail padding. This is allowed to
2022 // kick in for struct {double,int} on the int, but not on
2023 // struct{double,int,int} because we wouldn't return the second int. We
2024 // have to do this analysis on the source type because we can't depend on
2025 // unions being lowered a specific way etc.
2026 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002027 IRType->isIntegerTy(32) ||
2028 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2029 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2030 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002031
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002032 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2033 SourceOffset*8+64, getContext()))
2034 return IRType;
2035 }
2036 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002037
Chris Lattner2192fe52011-07-18 04:24:23 +00002038 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002039 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002040 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002041 if (IROffset < SL->getSizeInBytes()) {
2042 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2043 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002044
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002045 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2046 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002047 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002048 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002049
Chris Lattner2192fe52011-07-18 04:24:23 +00002050 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002051 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002052 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002053 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002054 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2055 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002056 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002057
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002058 // Okay, we don't have any better idea of what to pass, so we pass this in an
2059 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002060 unsigned TySizeInBytes =
2061 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002062
Chris Lattner3f763422010-07-29 17:34:39 +00002063 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002064
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002065 // It is always safe to classify this as an integer type up to i64 that
2066 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002067 return llvm::IntegerType::get(getVMContext(),
2068 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002069}
2070
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002071
2072/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2073/// be used as elements of a two register pair to pass or return, return a
2074/// first class aggregate to represent them. For example, if the low part of
2075/// a by-value argument should be passed as i32* and the high part as float,
2076/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002077static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002078GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002079 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002080 // In order to correctly satisfy the ABI, we need to the high part to start
2081 // at offset 8. If the high and low parts we inferred are both 4-byte types
2082 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2083 // the second element at offset 8. Check for this:
2084 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2085 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002086 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002087 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002088
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002089 // To handle this, we have to increase the size of the low part so that the
2090 // second element will start at an 8 byte offset. We can't increase the size
2091 // of the second element because it might make us access off the end of the
2092 // struct.
2093 if (HiStart != 8) {
2094 // There are only two sorts of types the ABI generation code can produce for
2095 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2096 // Promote these to a larger type.
2097 if (Lo->isFloatTy())
2098 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2099 else {
2100 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2101 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2102 }
2103 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002104
Chris Lattnera5f58b02011-07-09 17:41:47 +00002105 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002106
2107
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002108 // Verify that the second element is at an 8-byte offset.
2109 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2110 "Invalid x86-64 argument pair!");
2111 return Result;
2112}
2113
Chris Lattner31faff52010-07-28 23:06:14 +00002114ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002115classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002116 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2117 // classification algorithm.
2118 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002119 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002120
2121 // Check some invariants.
2122 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002123 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2124
Chris Lattnera5f58b02011-07-09 17:41:47 +00002125 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002126 switch (Lo) {
2127 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002128 if (Hi == NoClass)
2129 return ABIArgInfo::getIgnore();
2130 // If the low part is just padding, it takes no register, leave ResType
2131 // null.
2132 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2133 "Unknown missing lo part");
2134 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002135
2136 case SSEUp:
2137 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002138 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002139
2140 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2141 // hidden argument.
2142 case Memory:
2143 return getIndirectReturnResult(RetTy);
2144
2145 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2146 // available register of the sequence %rax, %rdx is used.
2147 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002148 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002149
Chris Lattner1f3a0632010-07-29 21:42:50 +00002150 // If we have a sign or zero extended integer, make sure to return Extend
2151 // so that the parameter gets the right LLVM IR attributes.
2152 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2153 // Treat an enum type as its underlying type.
2154 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2155 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002156
Chris Lattner1f3a0632010-07-29 21:42:50 +00002157 if (RetTy->isIntegralOrEnumerationType() &&
2158 RetTy->isPromotableIntegerType())
2159 return ABIArgInfo::getExtend();
2160 }
Chris Lattner31faff52010-07-28 23:06:14 +00002161 break;
2162
2163 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2164 // available SSE register of the sequence %xmm0, %xmm1 is used.
2165 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002166 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002167 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002168
2169 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2170 // returned on the X87 stack in %st0 as 80-bit x87 number.
2171 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002172 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002173 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002174
2175 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2176 // part of the value is returned in %st0 and the imaginary part in
2177 // %st1.
2178 case ComplexX87:
2179 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002180 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002181 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002182 NULL);
2183 break;
2184 }
2185
Chris Lattnera5f58b02011-07-09 17:41:47 +00002186 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002187 switch (Hi) {
2188 // Memory was handled previously and X87 should
2189 // never occur as a hi class.
2190 case Memory:
2191 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002192 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002193
2194 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002195 case NoClass:
2196 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002197
Chris Lattner52b3c132010-09-01 00:20:33 +00002198 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002199 HighPart = GetINTEGERTypeAtOffset(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;
Chris Lattner52b3c132010-09-01 00:20:33 +00002203 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002204 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002205 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2206 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002207 break;
2208
2209 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002210 // is passed in the next available eightbyte chunk if the last used
2211 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002212 //
Chris Lattner57540c52011-04-15 05:22:18 +00002213 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002214 case SSEUp:
2215 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002216 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002217 break;
2218
2219 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2220 // returned together with the previous X87 value in %st0.
2221 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002222 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002223 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002224 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002225 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002226 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002227 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002228 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2229 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002230 }
Chris Lattner31faff52010-07-28 23:06:14 +00002231 break;
2232 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002233
Chris Lattner52b3c132010-09-01 00:20:33 +00002234 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002235 // known to pass in the high eightbyte of the result. We do this by forming a
2236 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002237 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002238 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002239
Chris Lattner1f3a0632010-07-29 21:42:50 +00002240 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002241}
2242
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002243ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002244 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2245 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002246 const
2247{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002248 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002249 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002250
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002251 // Check some invariants.
2252 // FIXME: Enforce these by construction.
2253 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002254 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2255
2256 neededInt = 0;
2257 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002258 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002259 switch (Lo) {
2260 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002261 if (Hi == NoClass)
2262 return ABIArgInfo::getIgnore();
2263 // If the low part is just padding, it takes no register, leave ResType
2264 // null.
2265 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2266 "Unknown missing lo part");
2267 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002268
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002269 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2270 // on the stack.
2271 case Memory:
2272
2273 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2274 // COMPLEX_X87, it is passed in memory.
2275 case X87:
2276 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002277 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002278 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002279 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002280
2281 case SSEUp:
2282 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002283 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002284
2285 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2286 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2287 // and %r9 is used.
2288 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002289 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002290
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002291 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002292 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002293
2294 // If we have a sign or zero extended integer, make sure to return Extend
2295 // so that the parameter gets the right LLVM IR attributes.
2296 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2297 // Treat an enum type as its underlying type.
2298 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2299 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002300
Chris Lattner1f3a0632010-07-29 21:42:50 +00002301 if (Ty->isIntegralOrEnumerationType() &&
2302 Ty->isPromotableIntegerType())
2303 return ABIArgInfo::getExtend();
2304 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002305
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002306 break;
2307
2308 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2309 // available SSE register is used, the registers are taken in the
2310 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002311 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002312 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002313 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002314 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002315 break;
2316 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002317 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002318
Chris Lattnera5f58b02011-07-09 17:41:47 +00002319 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002320 switch (Hi) {
2321 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002322 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002323 // which is passed in memory.
2324 case Memory:
2325 case X87:
2326 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002327 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002328
2329 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002330
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002331 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002332 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002333 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002334 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002335
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002336 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2337 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 break;
2339
2340 // X87Up generally doesn't occur here (long double is passed in
2341 // memory), except in situations involving unions.
2342 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002343 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002344 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002345
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002346 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2347 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002348
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002349 ++neededSSE;
2350 break;
2351
2352 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2353 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002354 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002355 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002356 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002357 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002358 break;
2359 }
2360
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002361 // If a high part was specified, merge it together with the low part. It is
2362 // known to pass in the high eightbyte of the result. We do this by forming a
2363 // first class struct aggregate with the high and low part: {low, high}
2364 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002365 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002366
Chris Lattner1f3a0632010-07-29 21:42:50 +00002367 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002368}
2369
Chris Lattner22326a12010-07-29 02:31:05 +00002370void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002371
Chris Lattner458b2aa2010-07-29 02:16:43 +00002372 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002373
2374 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002375 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002376
2377 // If the return value is indirect, then the hidden argument is consuming one
2378 // integer register.
2379 if (FI.getReturnInfo().isIndirect())
2380 --freeIntRegs;
2381
Eli Friedman96fd2642013-06-12 00:13:45 +00002382 bool isVariadic = FI.isVariadic();
2383 unsigned numRequiredArgs = 0;
2384 if (isVariadic)
2385 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2386
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002387 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2388 // get assigned (in left-to-right order) for passing as follows...
2389 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2390 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002391 bool isNamedArg = true;
2392 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002393 isNamedArg = (it - FI.arg_begin()) <
2394 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002395
Bill Wendling9987c0e2010-10-18 23:51:38 +00002396 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002397 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002398 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002399
2400 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2401 // eightbyte of an argument, the whole argument is passed on the
2402 // stack. If registers have already been assigned for some
2403 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002404 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002405 freeIntRegs -= neededInt;
2406 freeSSERegs -= neededSSE;
2407 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002408 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002409 }
2410 }
2411}
2412
2413static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2414 QualType Ty,
2415 CodeGenFunction &CGF) {
2416 llvm::Value *overflow_arg_area_p =
2417 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2418 llvm::Value *overflow_arg_area =
2419 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2420
2421 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2422 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002423 // It isn't stated explicitly in the standard, but in practice we use
2424 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2426 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002427 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002428 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002429 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002430 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2431 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002432 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002433 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002434 overflow_arg_area =
2435 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2436 overflow_arg_area->getType(),
2437 "overflow_arg_area.align");
2438 }
2439
2440 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002441 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442 llvm::Value *Res =
2443 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002444 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002445
2446 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2447 // l->overflow_arg_area + sizeof(type).
2448 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2449 // an 8 byte boundary.
2450
2451 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002452 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002453 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2455 "overflow_arg_area.next");
2456 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2457
2458 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2459 return Res;
2460}
2461
2462llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2463 CodeGenFunction &CGF) const {
2464 // Assume that va_list type is correct; should be pointer to LLVM type:
2465 // struct {
2466 // i32 gp_offset;
2467 // i32 fp_offset;
2468 // i8* overflow_arg_area;
2469 // i8* reg_save_area;
2470 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002471 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002472
Chris Lattner9723d6c2010-03-11 18:19:55 +00002473 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002474 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2475 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002476
2477 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2478 // in the registers. If not go to step 7.
2479 if (!neededInt && !neededSSE)
2480 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2481
2482 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2483 // general purpose registers needed to pass type and num_fp to hold
2484 // the number of floating point registers needed.
2485
2486 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2487 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2488 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2489 //
2490 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2491 // register save space).
2492
2493 llvm::Value *InRegs = 0;
2494 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2495 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2496 if (neededInt) {
2497 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2498 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002499 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2500 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002501 }
2502
2503 if (neededSSE) {
2504 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2505 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2506 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002507 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2508 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2510 }
2511
2512 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2513 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2514 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2515 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2516
2517 // Emit code to load the value if it was passed in registers.
2518
2519 CGF.EmitBlock(InRegBlock);
2520
2521 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2522 // an offset of l->gp_offset and/or l->fp_offset. This may require
2523 // copying to a temporary location in case the parameter is passed
2524 // in different register classes or requires an alignment greater
2525 // than 8 for general purpose registers and 16 for XMM registers.
2526 //
2527 // FIXME: This really results in shameful code when we end up needing to
2528 // collect arguments from different places; often what should result in a
2529 // simple assembling of a structure from scattered addresses has many more
2530 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002531 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 llvm::Value *RegAddr =
2533 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2534 "reg_save_area");
2535 if (neededInt && neededSSE) {
2536 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002537 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002538 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002539 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2540 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002541 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002542 llvm::Type *TyLo = ST->getElementType(0);
2543 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002544 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002545 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002546 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2547 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002548 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2549 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002550 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2551 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002552 llvm::Value *V =
2553 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2554 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2555 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2556 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2557
Owen Anderson170229f2009-07-14 23:10:40 +00002558 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002559 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560 } else if (neededInt) {
2561 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2562 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002563 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002564
2565 // Copy to a temporary if necessary to ensure the appropriate alignment.
2566 std::pair<CharUnits, CharUnits> SizeAlign =
2567 CGF.getContext().getTypeInfoInChars(Ty);
2568 uint64_t TySize = SizeAlign.first.getQuantity();
2569 unsigned TyAlign = SizeAlign.second.getQuantity();
2570 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002571 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2572 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2573 RegAddr = Tmp;
2574 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002575 } else if (neededSSE == 1) {
2576 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2577 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2578 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002579 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002580 assert(neededSSE == 2 && "Invalid number of needed registers!");
2581 // SSE registers are spaced 16 bytes apart in the register save
2582 // area, we need to collect the two eightbytes together.
2583 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002584 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002585 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002586 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002587 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002588 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2589 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2590 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002591 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2592 DblPtrTy));
2593 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2594 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2595 DblPtrTy));
2596 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2597 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2598 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002599 }
2600
2601 // AMD64-ABI 3.5.7p5: Step 5. Set:
2602 // l->gp_offset = l->gp_offset + num_gp * 8
2603 // l->fp_offset = l->fp_offset + num_fp * 16.
2604 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002605 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002606 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2607 gp_offset_p);
2608 }
2609 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002610 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002611 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2612 fp_offset_p);
2613 }
2614 CGF.EmitBranch(ContBlock);
2615
2616 // Emit code to load the value if it was passed in memory.
2617
2618 CGF.EmitBlock(InMemBlock);
2619 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2620
2621 // Return the appropriate result.
2622
2623 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002624 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626 ResAddr->addIncoming(RegAddr, InRegBlock);
2627 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002628 return ResAddr;
2629}
2630
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002631ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002632
2633 if (Ty->isVoidType())
2634 return ABIArgInfo::getIgnore();
2635
2636 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2637 Ty = EnumTy->getDecl()->getIntegerType();
2638
2639 uint64_t Size = getContext().getTypeSize(Ty);
2640
2641 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002642 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002643 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002644 return ABIArgInfo::getIndirect(0, false);
2645 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002646 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002647 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2648 }
2649
2650 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002651 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2652
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002653 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002654 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002655 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2656 Size));
2657
2658 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2659 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2660 if (Size <= 64 &&
NAKAMURA Takumie03c6032011-01-19 00:11:33 +00002661 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002662 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2663 Size));
2664
2665 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2666 }
2667
2668 if (Ty->isPromotableIntegerType())
2669 return ABIArgInfo::getExtend();
2670
2671 return ABIArgInfo::getDirect();
2672}
2673
2674void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2675
2676 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002677 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002678
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002679 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2680 it != ie; ++it)
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002681 it->info = classify(it->type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002682}
2683
Chris Lattner04dc9572010-08-31 16:44:54 +00002684llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2685 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002686 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002687
Chris Lattner04dc9572010-08-31 16:44:54 +00002688 CGBuilderTy &Builder = CGF.Builder;
2689 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2690 "ap");
2691 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2692 llvm::Type *PTy =
2693 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2694 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2695
2696 uint64_t Offset =
2697 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2698 llvm::Value *NextAddr =
2699 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2700 "ap.next");
2701 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2702
2703 return AddrTyped;
2704}
Chris Lattner0cf24192010-06-28 20:05:43 +00002705
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002706namespace {
2707
Derek Schuffa2020962012-10-16 22:30:41 +00002708class NaClX86_64ABIInfo : public ABIInfo {
2709 public:
2710 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2711 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2712 virtual void computeInfo(CGFunctionInfo &FI) const;
2713 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2714 CodeGenFunction &CGF) const;
2715 private:
2716 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2717 X86_64ABIInfo NInfo; // Used for everything else.
2718};
2719
2720class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2721 public:
2722 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2723 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2724};
2725
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002726}
2727
Derek Schuffa2020962012-10-16 22:30:41 +00002728void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2729 if (FI.getASTCallingConvention() == CC_PnaclCall)
2730 PInfo.computeInfo(FI);
2731 else
2732 NInfo.computeInfo(FI);
2733}
2734
2735llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2736 CodeGenFunction &CGF) const {
2737 // Always use the native convention; calling pnacl-style varargs functions
2738 // is unuspported.
2739 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2740}
2741
2742
John McCallea8d8bb2010-03-11 00:10:12 +00002743// PowerPC-32
2744
2745namespace {
2746class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2747public:
Chris Lattner2b037972010-07-29 02:01:43 +00002748 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002749
John McCallea8d8bb2010-03-11 00:10:12 +00002750 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2751 // This is recovered from gcc output.
2752 return 1; // r1 is the dedicated stack pointer
2753 }
2754
2755 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002756 llvm::Value *Address) const;
John McCallea8d8bb2010-03-11 00:10:12 +00002757};
2758
2759}
2760
2761bool
2762PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2763 llvm::Value *Address) const {
2764 // This is calculated from the LLVM and GCC tables and verified
2765 // against gcc output. AFAIK all ABIs use the same encoding.
2766
2767 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002768
Chris Lattnerece04092012-02-07 00:39:47 +00002769 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002770 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2771 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2772 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2773
2774 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002775 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002776
2777 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002778 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002779
2780 // 64-76 are various 4-byte special-purpose registers:
2781 // 64: mq
2782 // 65: lr
2783 // 66: ctr
2784 // 67: ap
2785 // 68-75 cr0-7
2786 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002787 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002788
2789 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002790 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002791
2792 // 109: vrsave
2793 // 110: vscr
2794 // 111: spe_acc
2795 // 112: spefscr
2796 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002797 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002798
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002799 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002800}
2801
Roman Divackyd966e722012-05-09 18:22:46 +00002802// PowerPC-64
2803
2804namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002805/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2806class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2807
2808public:
2809 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2810
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002811 bool isPromotableTypeForABI(QualType Ty) const;
2812
2813 ABIArgInfo classifyReturnType(QualType RetTy) const;
2814 ABIArgInfo classifyArgumentType(QualType Ty) const;
2815
Bill Schmidt84d37792012-10-12 19:26:17 +00002816 // TODO: We can add more logic to computeInfo to improve performance.
2817 // Example: For aggregate arguments that fit in a register, we could
2818 // use getDirectInReg (as is done below for structs containing a single
2819 // floating-point value) to avoid pushing them to memory on function
2820 // entry. This would require changing the logic in PPCISelLowering
2821 // when lowering the parameters in the caller and args in the callee.
2822 virtual void computeInfo(CGFunctionInfo &FI) const {
2823 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2824 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2825 it != ie; ++it) {
2826 // We rely on the default argument classification for the most part.
2827 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002828 // or vector item must be passed in a register if one is available.
Bill Schmidt84d37792012-10-12 19:26:17 +00002829 const Type *T = isSingleElementStruct(it->type, getContext());
2830 if (T) {
2831 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002832 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002833 QualType QT(T, 0);
2834 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2835 continue;
2836 }
2837 }
2838 it->info = classifyArgumentType(it->type);
2839 }
2840 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002841
2842 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2843 QualType Ty,
2844 CodeGenFunction &CGF) const;
2845};
2846
2847class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2848public:
2849 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2850 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2851
2852 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2853 // This is recovered from gcc output.
2854 return 1; // r1 is the dedicated stack pointer
2855 }
2856
2857 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2858 llvm::Value *Address) const;
2859};
2860
Roman Divackyd966e722012-05-09 18:22:46 +00002861class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2862public:
2863 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2864
2865 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2866 // This is recovered from gcc output.
2867 return 1; // r1 is the dedicated stack pointer
2868 }
2869
2870 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2871 llvm::Value *Address) const;
2872};
2873
2874}
2875
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002876// Return true if the ABI requires Ty to be passed sign- or zero-
2877// extended to 64 bits.
2878bool
2879PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2880 // Treat an enum type as its underlying type.
2881 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2882 Ty = EnumTy->getDecl()->getIntegerType();
2883
2884 // Promotable integer types are required to be promoted by the ABI.
2885 if (Ty->isPromotableIntegerType())
2886 return true;
2887
2888 // In addition to the usual promotable integer types, we also need to
2889 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2890 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2891 switch (BT->getKind()) {
2892 case BuiltinType::Int:
2893 case BuiltinType::UInt:
2894 return true;
2895 default:
2896 break;
2897 }
2898
2899 return false;
2900}
2901
2902ABIArgInfo
2903PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002904 if (Ty->isAnyComplexType())
2905 return ABIArgInfo::getDirect();
2906
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002907 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002908 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002909 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002910
2911 return ABIArgInfo::getIndirect(0);
2912 }
2913
2914 return (isPromotableTypeForABI(Ty) ?
2915 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2916}
2917
2918ABIArgInfo
2919PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2920 if (RetTy->isVoidType())
2921 return ABIArgInfo::getIgnore();
2922
Bill Schmidta3d121c2012-12-17 04:20:17 +00002923 if (RetTy->isAnyComplexType())
2924 return ABIArgInfo::getDirect();
2925
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002926 if (isAggregateTypeForABI(RetTy))
2927 return ABIArgInfo::getIndirect(0);
2928
2929 return (isPromotableTypeForABI(RetTy) ?
2930 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2931}
2932
Bill Schmidt25cb3492012-10-03 19:18:57 +00002933// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2934llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2935 QualType Ty,
2936 CodeGenFunction &CGF) const {
2937 llvm::Type *BP = CGF.Int8PtrTy;
2938 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2939
2940 CGBuilderTy &Builder = CGF.Builder;
2941 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2942 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2943
Bill Schmidt924c4782013-01-14 17:45:36 +00002944 // Update the va_list pointer. The pointer should be bumped by the
2945 // size of the object. We can trust getTypeSize() except for a complex
2946 // type whose base type is smaller than a doubleword. For these, the
2947 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00002948 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00002949 QualType BaseTy;
2950 unsigned CplxBaseSize = 0;
2951
2952 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2953 BaseTy = CTy->getElementType();
2954 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2955 if (CplxBaseSize < 8)
2956 SizeInBytes = 16;
2957 }
2958
Bill Schmidt25cb3492012-10-03 19:18:57 +00002959 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2960 llvm::Value *NextAddr =
2961 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2962 "ap.next");
2963 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2964
Bill Schmidt924c4782013-01-14 17:45:36 +00002965 // If we have a complex type and the base type is smaller than 8 bytes,
2966 // the ABI calls for the real and imaginary parts to be right-adjusted
2967 // in separate doublewords. However, Clang expects us to produce a
2968 // pointer to a structure with the two parts packed tightly. So generate
2969 // loads of the real and imaginary parts relative to the va_list pointer,
2970 // and store them to a temporary structure.
2971 if (CplxBaseSize && CplxBaseSize < 8) {
2972 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2973 llvm::Value *ImagAddr = RealAddr;
2974 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2975 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2976 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2977 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2978 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2979 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2980 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2981 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2982 "vacplx");
2983 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2984 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2985 Builder.CreateStore(Real, RealPtr, false);
2986 Builder.CreateStore(Imag, ImagPtr, false);
2987 return Ptr;
2988 }
2989
Bill Schmidt25cb3492012-10-03 19:18:57 +00002990 // If the argument is smaller than 8 bytes, it is right-adjusted in
2991 // its doubleword slot. Adjust the pointer to pick it up from the
2992 // correct offset.
2993 if (SizeInBytes < 8) {
2994 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2995 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2996 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2997 }
2998
2999 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3000 return Builder.CreateBitCast(Addr, PTy);
3001}
3002
3003static bool
3004PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3005 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003006 // This is calculated from the LLVM and GCC tables and verified
3007 // against gcc output. AFAIK all ABIs use the same encoding.
3008
3009 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3010
3011 llvm::IntegerType *i8 = CGF.Int8Ty;
3012 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3013 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3014 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3015
3016 // 0-31: r0-31, the 8-byte general-purpose registers
3017 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3018
3019 // 32-63: fp0-31, the 8-byte floating-point registers
3020 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3021
3022 // 64-76 are various 4-byte special-purpose registers:
3023 // 64: mq
3024 // 65: lr
3025 // 66: ctr
3026 // 67: ap
3027 // 68-75 cr0-7
3028 // 76: xer
3029 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3030
3031 // 77-108: v0-31, the 16-byte vector registers
3032 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3033
3034 // 109: vrsave
3035 // 110: vscr
3036 // 111: spe_acc
3037 // 112: spefscr
3038 // 113: sfp
3039 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3040
3041 return false;
3042}
John McCallea8d8bb2010-03-11 00:10:12 +00003043
Bill Schmidt25cb3492012-10-03 19:18:57 +00003044bool
3045PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3046 CodeGen::CodeGenFunction &CGF,
3047 llvm::Value *Address) const {
3048
3049 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3050}
3051
3052bool
3053PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3054 llvm::Value *Address) const {
3055
3056 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3057}
3058
Chris Lattner0cf24192010-06-28 20:05:43 +00003059//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003060// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003061//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003062
3063namespace {
3064
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003065class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003066public:
3067 enum ABIKind {
3068 APCS = 0,
3069 AAPCS = 1,
3070 AAPCS_VFP
3071 };
3072
3073private:
3074 ABIKind Kind;
3075
3076public:
John McCall882987f2013-02-28 19:01:20 +00003077 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3078 setRuntimeCC();
3079 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003080
John McCall3480ef22011-08-30 01:42:09 +00003081 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003082 switch (getTarget().getTriple().getEnvironment()) {
3083 case llvm::Triple::Android:
3084 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003085 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003086 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003087 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003088 return true;
3089 default:
3090 return false;
3091 }
John McCall3480ef22011-08-30 01:42:09 +00003092 }
3093
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003094 bool isEABIHF() const {
3095 switch (getTarget().getTriple().getEnvironment()) {
3096 case llvm::Triple::EABIHF:
3097 case llvm::Triple::GNUEABIHF:
3098 return true;
3099 default:
3100 return false;
3101 }
3102 }
3103
Daniel Dunbar020daa92009-09-12 01:00:39 +00003104 ABIKind getABIKind() const { return Kind; }
3105
Tim Northovera484bc02013-10-01 14:34:25 +00003106private:
Amara Emerson9dc78782014-01-28 10:56:36 +00003107 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Manman Renb505d332012-10-31 19:02:26 +00003108 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3109 unsigned &AllocatedVFP,
Amara Emerson9dc78782014-01-28 10:56:36 +00003110 bool &IsHA, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00003111 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003112
Chris Lattner22326a12010-07-29 02:31:05 +00003113 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003114
3115 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3116 CodeGenFunction &CGF) const;
John McCall882987f2013-02-28 19:01:20 +00003117
3118 llvm::CallingConv::ID getLLVMDefaultCC() const;
3119 llvm::CallingConv::ID getABIDefaultCC() const;
3120 void setRuntimeCC();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003121};
3122
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003123class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3124public:
Chris Lattner2b037972010-07-29 02:01:43 +00003125 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3126 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003127
John McCall3480ef22011-08-30 01:42:09 +00003128 const ARMABIInfo &getABIInfo() const {
3129 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3130 }
3131
John McCallbeec5a02010-03-06 00:35:14 +00003132 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3133 return 13;
3134 }
Roman Divackyc1617352011-05-18 19:36:54 +00003135
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003136 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCall31168b02011-06-15 23:02:42 +00003137 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3138 }
3139
Roman Divackyc1617352011-05-18 19:36:54 +00003140 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3141 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003142 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003143
3144 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003145 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003146 return false;
3147 }
John McCall3480ef22011-08-30 01:42:09 +00003148
3149 unsigned getSizeOfUnwindException() const {
3150 if (getABIInfo().isEABI()) return 88;
3151 return TargetCodeGenInfo::getSizeOfUnwindException();
3152 }
Tim Northovera484bc02013-10-01 14:34:25 +00003153
3154 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3155 CodeGen::CodeGenModule &CGM) const {
3156 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3157 if (!FD)
3158 return;
3159
3160 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3161 if (!Attr)
3162 return;
3163
3164 const char *Kind;
3165 switch (Attr->getInterrupt()) {
3166 case ARMInterruptAttr::Generic: Kind = ""; break;
3167 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3168 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3169 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3170 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3171 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3172 }
3173
3174 llvm::Function *Fn = cast<llvm::Function>(GV);
3175
3176 Fn->addFnAttr("interrupt", Kind);
3177
3178 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3179 return;
3180
3181 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3182 // however this is not necessarily true on taking any interrupt. Instruct
3183 // the backend to perform a realignment as part of the function prologue.
3184 llvm::AttrBuilder B;
3185 B.addStackAlignmentAttr(8);
3186 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3187 llvm::AttributeSet::get(CGM.getLLVMContext(),
3188 llvm::AttributeSet::FunctionIndex,
3189 B));
3190 }
3191
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003192};
3193
Daniel Dunbard59655c2009-09-12 00:59:49 +00003194}
3195
Chris Lattner22326a12010-07-29 02:31:05 +00003196void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003197 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003198 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003199 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3200 // VFP registers of the appropriate type unallocated then the argument is
3201 // allocated to the lowest-numbered sequence of such registers.
3202 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3203 // unallocated are marked as unavailable.
3204 unsigned AllocatedVFP = 0;
Manman Renb505d332012-10-31 19:02:26 +00003205 int VFPRegs[16] = { 0 };
Amara Emerson9dc78782014-01-28 10:56:36 +00003206 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003207 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Ren2a523d82012-10-30 23:21:41 +00003208 it != ie; ++it) {
3209 unsigned PreAllocation = AllocatedVFP;
3210 bool IsHA = false;
3211 // 6.1.2.3 There is one VFP co-processor register class using registers
3212 // s0-s15 (d0-d7) for passing arguments.
3213 const unsigned NumVFPs = 16;
Amara Emerson9dc78782014-01-28 10:56:36 +00003214 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA, FI.isVariadic());
Manman Ren2a523d82012-10-30 23:21:41 +00003215 // If we do not have enough VFP registers for the HA, any VFP registers
3216 // that are unallocated are marked as unavailable. To achieve this, we add
3217 // padding of (NumVFPs - PreAllocation) floats.
Amara Emerson9dc78782014-01-28 10:56:36 +00003218 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3219 // and the callee is not variadic.
Manman Ren2a523d82012-10-30 23:21:41 +00003220 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3221 llvm::Type *PaddingTy = llvm::ArrayType::get(
3222 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3223 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3224 }
3225 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003226
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003227 // Always honor user-specified calling convention.
3228 if (FI.getCallingConvention() != llvm::CallingConv::C)
3229 return;
3230
John McCall882987f2013-02-28 19:01:20 +00003231 llvm::CallingConv::ID cc = getRuntimeCC();
3232 if (cc != llvm::CallingConv::C)
3233 FI.setEffectiveCallingConvention(cc);
3234}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003235
John McCall882987f2013-02-28 19:01:20 +00003236/// Return the default calling convention that LLVM will use.
3237llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3238 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003239 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003240 return llvm::CallingConv::ARM_AAPCS_VFP;
3241 else if (isEABI())
3242 return llvm::CallingConv::ARM_AAPCS;
3243 else
3244 return llvm::CallingConv::ARM_APCS;
3245}
3246
3247/// Return the calling convention that our ABI would like us to use
3248/// as the C calling convention.
3249llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003250 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003251 case APCS: return llvm::CallingConv::ARM_APCS;
3252 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3253 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003254 }
John McCall882987f2013-02-28 19:01:20 +00003255 llvm_unreachable("bad ABI kind");
3256}
3257
3258void ARMABIInfo::setRuntimeCC() {
3259 assert(getRuntimeCC() == llvm::CallingConv::C);
3260
3261 // Don't muddy up the IR with a ton of explicit annotations if
3262 // they'd just match what LLVM will infer from the triple.
3263 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3264 if (abiCC != getLLVMDefaultCC())
3265 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003266}
3267
Bob Wilsone826a2a2011-08-03 05:58:22 +00003268/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3269/// aggregate. If HAMembers is non-null, the number of base elements
3270/// contained in the type is returned through it; this is used for the
3271/// recursive calls that check aggregate component types.
3272static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3273 ASTContext &Context,
3274 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003275 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003276 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3277 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3278 return false;
3279 Members *= AT->getSize().getZExtValue();
3280 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3281 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003282 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003283 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003284
Bob Wilsone826a2a2011-08-03 05:58:22 +00003285 Members = 0;
3286 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3287 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003288 const FieldDecl *FD = *i;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003289 uint64_t FldMembers;
3290 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3291 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003292
3293 Members = (RD->isUnion() ?
3294 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003295 }
3296 } else {
3297 Members = 1;
3298 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3299 Members = 2;
3300 Ty = CT->getElementType();
3301 }
3302
3303 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3304 // double, or 64-bit or 128-bit vectors.
3305 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3306 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003307 BT->getKind() != BuiltinType::Double &&
3308 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003309 return false;
3310 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3311 unsigned VecSize = Context.getTypeSize(VT);
3312 if (VecSize != 64 && VecSize != 128)
3313 return false;
3314 } else {
3315 return false;
3316 }
3317
3318 // The base type must be the same for all members. Vector types of the
3319 // same total size are treated as being equivalent here.
3320 const Type *TyPtr = Ty.getTypePtr();
3321 if (!Base)
3322 Base = TyPtr;
3323 if (Base != TyPtr &&
3324 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3325 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3326 return false;
3327 }
3328
3329 // Homogeneous Aggregates can have at most 4 members of the base type.
3330 if (HAMembers)
3331 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003332
3333 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003334}
3335
Manman Renb505d332012-10-31 19:02:26 +00003336/// markAllocatedVFPs - update VFPRegs according to the alignment and
3337/// number of VFP registers (unit is S register) requested.
3338static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3339 unsigned Alignment,
3340 unsigned NumRequired) {
3341 // Early Exit.
3342 if (AllocatedVFP >= 16)
3343 return;
3344 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3345 // VFP registers of the appropriate type unallocated then the argument is
3346 // allocated to the lowest-numbered sequence of such registers.
3347 for (unsigned I = 0; I < 16; I += Alignment) {
3348 bool FoundSlot = true;
3349 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3350 if (J >= 16 || VFPRegs[J]) {
3351 FoundSlot = false;
3352 break;
3353 }
3354 if (FoundSlot) {
3355 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3356 VFPRegs[J] = 1;
3357 AllocatedVFP += NumRequired;
3358 return;
3359 }
3360 }
3361 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3362 // unallocated are marked as unavailable.
3363 for (unsigned I = 0; I < 16; I++)
3364 VFPRegs[I] = 1;
3365 AllocatedVFP = 17; // We do not have enough VFP registers.
3366}
3367
3368ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3369 unsigned &AllocatedVFP,
Amara Emerson9dc78782014-01-28 10:56:36 +00003370 bool &IsHA, bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003371 // We update number of allocated VFPs according to
3372 // 6.1.2.1 The following argument types are VFP CPRCs:
3373 // A single-precision floating-point type (including promoted
3374 // half-precision types); A double-precision floating-point type;
3375 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3376 // with a Base Type of a single- or double-precision floating-point type,
3377 // 64-bit containerized vectors or 128-bit containerized vectors with one
3378 // to four Elements.
3379
Manman Renfef9e312012-10-16 19:18:39 +00003380 // Handle illegal vector types here.
3381 if (isIllegalVectorType(Ty)) {
3382 uint64_t Size = getContext().getTypeSize(Ty);
3383 if (Size <= 32) {
3384 llvm::Type *ResType =
3385 llvm::Type::getInt32Ty(getVMContext());
3386 return ABIArgInfo::getDirect(ResType);
3387 }
3388 if (Size == 64) {
3389 llvm::Type *ResType = llvm::VectorType::get(
3390 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Renb505d332012-10-31 19:02:26 +00003391 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renfef9e312012-10-16 19:18:39 +00003392 return ABIArgInfo::getDirect(ResType);
3393 }
3394 if (Size == 128) {
3395 llvm::Type *ResType = llvm::VectorType::get(
3396 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Renb505d332012-10-31 19:02:26 +00003397 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Renfef9e312012-10-16 19:18:39 +00003398 return ABIArgInfo::getDirect(ResType);
3399 }
3400 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3401 }
Manman Renb505d332012-10-31 19:02:26 +00003402 // Update VFPRegs for legal vector types.
Manman Ren2a523d82012-10-30 23:21:41 +00003403 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3404 uint64_t Size = getContext().getTypeSize(VT);
3405 // Size of a legal vector should be power of 2 and above 64.
Manman Renb505d332012-10-31 19:02:26 +00003406 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Ren2a523d82012-10-30 23:21:41 +00003407 }
Manman Renb505d332012-10-31 19:02:26 +00003408 // Update VFPRegs for floating point types.
Manman Ren2a523d82012-10-30 23:21:41 +00003409 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3410 if (BT->getKind() == BuiltinType::Half ||
3411 BT->getKind() == BuiltinType::Float)
Manman Renb505d332012-10-31 19:02:26 +00003412 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Ren2a523d82012-10-30 23:21:41 +00003413 if (BT->getKind() == BuiltinType::Double ||
Manman Renb505d332012-10-31 19:02:26 +00003414 BT->getKind() == BuiltinType::LongDouble)
3415 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003416 }
Manman Renfef9e312012-10-16 19:18:39 +00003417
John McCalla1dee5302010-08-22 10:59:02 +00003418 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003419 // Treat an enum type as its underlying type.
3420 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3421 Ty = EnumTy->getDecl()->getIntegerType();
3422
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003423 return (Ty->isPromotableIntegerType() ?
3424 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003425 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003426
Mark Lacey3825e832013-10-06 01:33:34 +00003427 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Tim Northover1060eae2013-06-21 22:49:34 +00003428 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3429
Daniel Dunbar09d33622009-09-14 21:54:03 +00003430 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003431 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003432 return ABIArgInfo::getIgnore();
3433
Amara Emerson9dc78782014-01-28 10:56:36 +00003434 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00003435 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3436 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003437 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003438 uint64_t Members = 0;
3439 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003440 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003441 // Base can be a floating-point or a vector.
3442 if (Base->isVectorType()) {
3443 // ElementSize is in number of floats.
3444 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Ren77b02382012-11-06 19:05:29 +00003445 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3446 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003447 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Renb505d332012-10-31 19:02:26 +00003448 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003449 else {
3450 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3451 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Renb505d332012-10-31 19:02:26 +00003452 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003453 }
3454 IsHA = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003455 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003456 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003457 }
3458
Manman Ren6c30e132012-08-13 21:23:55 +00003459 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003460 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3461 // most 8-byte. We realign the indirect argument if type alignment is bigger
3462 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003463 uint64_t ABIAlign = 4;
3464 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3465 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3466 getABIKind() == ARMABIInfo::AAPCS)
3467 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003468 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3469 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003470 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003471 }
3472
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003473 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003474 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003475 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003476 // FIXME: Try to match the types of the arguments more accurately where
3477 // we can.
3478 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003479 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3480 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00003481 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003482 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3483 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003484 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003485
Chris Lattnera5f58b02011-07-09 17:41:47 +00003486 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003487 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003488 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003489}
3490
Chris Lattner458b2aa2010-07-29 02:16:43 +00003491static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003492 llvm::LLVMContext &VMContext) {
3493 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3494 // is called integer-like if its size is less than or equal to one word, and
3495 // the offset of each of its addressable sub-fields is zero.
3496
3497 uint64_t Size = Context.getTypeSize(Ty);
3498
3499 // Check that the type fits in a word.
3500 if (Size > 32)
3501 return false;
3502
3503 // FIXME: Handle vector types!
3504 if (Ty->isVectorType())
3505 return false;
3506
Daniel Dunbard53bac72009-09-14 02:20:34 +00003507 // Float types are never treated as "integer like".
3508 if (Ty->isRealFloatingType())
3509 return false;
3510
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003511 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003512 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003513 return true;
3514
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003515 // Small complex integer types are "integer like".
3516 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3517 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003518
3519 // Single element and zero sized arrays should be allowed, by the definition
3520 // above, but they are not.
3521
3522 // Otherwise, it must be a record type.
3523 const RecordType *RT = Ty->getAs<RecordType>();
3524 if (!RT) return false;
3525
3526 // Ignore records with flexible arrays.
3527 const RecordDecl *RD = RT->getDecl();
3528 if (RD->hasFlexibleArrayMember())
3529 return false;
3530
3531 // Check that all sub-fields are at offset 0, and are themselves "integer
3532 // like".
3533 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3534
3535 bool HadField = false;
3536 unsigned idx = 0;
3537 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3538 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003539 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003540
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003541 // Bit-fields are not addressable, we only need to verify they are "integer
3542 // like". We still have to disallow a subsequent non-bitfield, for example:
3543 // struct { int : 0; int x }
3544 // is non-integer like according to gcc.
3545 if (FD->isBitField()) {
3546 if (!RD->isUnion())
3547 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003548
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003549 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3550 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003551
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003552 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003553 }
3554
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003555 // Check if this field is at offset 0.
3556 if (Layout.getFieldOffset(idx) != 0)
3557 return false;
3558
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003559 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3560 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003561
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003562 // Only allow at most one field in a structure. This doesn't match the
3563 // wording above, but follows gcc in situations with a field following an
3564 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003565 if (!RD->isUnion()) {
3566 if (HadField)
3567 return false;
3568
3569 HadField = true;
3570 }
3571 }
3572
3573 return true;
3574}
3575
Amara Emerson9dc78782014-01-28 10:56:36 +00003576ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003577 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003578 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003579
Daniel Dunbar19964db2010-09-23 01:54:32 +00003580 // Large vector types should be returned via memory.
3581 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3582 return ABIArgInfo::getIndirect(0);
3583
John McCalla1dee5302010-08-22 10:59:02 +00003584 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003585 // Treat an enum type as its underlying type.
3586 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3587 RetTy = EnumTy->getDecl()->getIntegerType();
3588
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003589 return (RetTy->isPromotableIntegerType() ?
3590 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003591 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003592
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003593 // Structures with either a non-trivial destructor or a non-trivial
3594 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00003595 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003596 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3597
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003598 // Are we following APCS?
3599 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003600 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003601 return ABIArgInfo::getIgnore();
3602
Daniel Dunbareedf1512010-02-01 23:31:19 +00003603 // Complex types are all returned as packed integers.
3604 //
3605 // FIXME: Consider using 2 x vector types if the back end handles them
3606 // correctly.
3607 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003608 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003609 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003610
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003611 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003612 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003613 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003614 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003615 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003616 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003617 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003618 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3619 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003620 }
3621
3622 // Otherwise return in memory.
3623 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003624 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003625
3626 // Otherwise this is an AAPCS variant.
3627
Chris Lattner458b2aa2010-07-29 02:16:43 +00003628 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003629 return ABIArgInfo::getIgnore();
3630
Bob Wilson1d9269a2011-11-02 04:51:36 +00003631 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00003632 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson1d9269a2011-11-02 04:51:36 +00003633 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003634 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3635 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003636 // Homogeneous Aggregates are returned directly.
3637 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003638 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003639 }
3640
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003641 // Aggregates <= 4 bytes are returned in r0; other aggregates
3642 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003643 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003644 if (Size <= 32) {
3645 // Return in the smallest viable integer type.
3646 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003647 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003648 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003649 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3650 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003651 }
3652
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003653 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003654}
3655
Manman Renfef9e312012-10-16 19:18:39 +00003656/// isIllegalVector - check whether Ty is an illegal vector type.
3657bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3658 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3659 // Check whether VT is legal.
3660 unsigned NumElements = VT->getNumElements();
3661 uint64_t Size = getContext().getTypeSize(VT);
3662 // NumElements should be power of 2.
3663 if ((NumElements & (NumElements - 1)) != 0)
3664 return true;
3665 // Size should be greater than 32 bits.
3666 return Size <= 32;
3667 }
3668 return false;
3669}
3670
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003671llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003672 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003673 llvm::Type *BP = CGF.Int8PtrTy;
3674 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003675
3676 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003677 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003678 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003679
Tim Northover1711cc92013-06-21 23:05:33 +00003680 if (isEmptyRecord(getContext(), Ty, true)) {
3681 // These are ignored for parameter passing purposes.
3682 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3683 return Builder.CreateBitCast(Addr, PTy);
3684 }
3685
Manman Rencca54d02012-10-16 19:01:37 +00003686 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003687 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003688 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003689
3690 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3691 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003692 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3693 getABIKind() == ARMABIInfo::AAPCS)
3694 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3695 else
3696 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003697 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3698 if (isIllegalVectorType(Ty) && Size > 16) {
3699 IsIndirect = true;
3700 Size = 4;
3701 TyAlign = 4;
3702 }
Manman Rencca54d02012-10-16 19:01:37 +00003703
3704 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003705 if (TyAlign > 4) {
3706 assert((TyAlign & (TyAlign - 1)) == 0 &&
3707 "Alignment is not power of 2!");
3708 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3709 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3710 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003711 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003712 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003713
3714 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003715 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003716 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003717 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003718 "ap.next");
3719 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3720
Manman Renfef9e312012-10-16 19:18:39 +00003721 if (IsIndirect)
3722 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003723 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003724 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3725 // may not be correctly aligned for the vector type. We create an aligned
3726 // temporary space and copy the content over from ap.cur to the temporary
3727 // space. This is necessary if the natural alignment of the type is greater
3728 // than the ABI alignment.
3729 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3730 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3731 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3732 "var.align");
3733 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3734 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3735 Builder.CreateMemCpy(Dst, Src,
3736 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3737 TyAlign, false);
3738 Addr = AlignedTemp; //The content is in aligned location.
3739 }
3740 llvm::Type *PTy =
3741 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3742 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3743
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003744 return AddrTyped;
3745}
3746
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003747namespace {
3748
Derek Schuffa2020962012-10-16 22:30:41 +00003749class NaClARMABIInfo : public ABIInfo {
3750 public:
3751 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3752 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3753 virtual void computeInfo(CGFunctionInfo &FI) const;
3754 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3755 CodeGenFunction &CGF) const;
3756 private:
3757 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3758 ARMABIInfo NInfo; // Used for everything else.
3759};
3760
3761class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3762 public:
3763 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3764 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3765};
3766
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003767}
3768
Derek Schuffa2020962012-10-16 22:30:41 +00003769void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3770 if (FI.getASTCallingConvention() == CC_PnaclCall)
3771 PInfo.computeInfo(FI);
3772 else
3773 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3774}
3775
3776llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3777 CodeGenFunction &CGF) const {
3778 // Always use the native convention; calling pnacl-style varargs functions
3779 // is unsupported.
3780 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3781}
3782
Chris Lattner0cf24192010-06-28 20:05:43 +00003783//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003784// AArch64 ABI Implementation
3785//===----------------------------------------------------------------------===//
3786
3787namespace {
3788
3789class AArch64ABIInfo : public ABIInfo {
3790public:
3791 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3792
3793private:
3794 // The AArch64 PCS is explicit about return types and argument types being
3795 // handled identically, so we don't need to draw a distinction between
3796 // Argument and Return classification.
3797 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3798 int &FreeVFPRegs) const;
3799
3800 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3801 llvm::Type *DirectTy = 0) const;
3802
3803 virtual void computeInfo(CGFunctionInfo &FI) const;
3804
3805 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3806 CodeGenFunction &CGF) const;
3807};
3808
3809class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3810public:
3811 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3812 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3813
3814 const AArch64ABIInfo &getABIInfo() const {
3815 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3816 }
3817
3818 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3819 return 31;
3820 }
3821
3822 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3823 llvm::Value *Address) const {
3824 // 0-31 are x0-x30 and sp: 8 bytes each
3825 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3826 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3827
3828 // 64-95 are v0-v31: 16 bytes each
3829 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3830 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3831
3832 return false;
3833 }
3834
3835};
3836
3837}
3838
3839void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3840 int FreeIntRegs = 8, FreeVFPRegs = 8;
3841
3842 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3843 FreeIntRegs, FreeVFPRegs);
3844
3845 FreeIntRegs = FreeVFPRegs = 8;
3846 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3847 it != ie; ++it) {
3848 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3849
3850 }
3851}
3852
3853ABIArgInfo
3854AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3855 bool IsInt, llvm::Type *DirectTy) const {
3856 if (FreeRegs >= RegsNeeded) {
3857 FreeRegs -= RegsNeeded;
3858 return ABIArgInfo::getDirect(DirectTy);
3859 }
3860
3861 llvm::Type *Padding = 0;
3862
3863 // We need padding so that later arguments don't get filled in anyway. That
3864 // wouldn't happen if only ByVal arguments followed in the same category, but
3865 // a large structure will simply seem to be a pointer as far as LLVM is
3866 // concerned.
3867 if (FreeRegs > 0) {
3868 if (IsInt)
3869 Padding = llvm::Type::getInt64Ty(getVMContext());
3870 else
3871 Padding = llvm::Type::getFloatTy(getVMContext());
3872
3873 // Either [N x i64] or [N x float].
3874 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3875 FreeRegs = 0;
3876 }
3877
3878 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3879 /*IsByVal=*/ true, /*Realign=*/ false,
3880 Padding);
3881}
3882
3883
3884ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3885 int &FreeIntRegs,
3886 int &FreeVFPRegs) const {
3887 // Can only occurs for return, but harmless otherwise.
3888 if (Ty->isVoidType())
3889 return ABIArgInfo::getIgnore();
3890
3891 // Large vector types should be returned via memory. There's no such concept
3892 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3893 // classified they'd go into memory (see B.3).
3894 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3895 if (FreeIntRegs > 0)
3896 --FreeIntRegs;
3897 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3898 }
3899
3900 // All non-aggregate LLVM types have a concrete ABI representation so they can
3901 // be passed directly. After this block we're guaranteed to be in a
3902 // complicated case.
3903 if (!isAggregateTypeForABI(Ty)) {
3904 // Treat an enum type as its underlying type.
3905 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3906 Ty = EnumTy->getDecl()->getIntegerType();
3907
3908 if (Ty->isFloatingType() || Ty->isVectorType())
3909 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3910
3911 assert(getContext().getTypeSize(Ty) <= 128 &&
3912 "unexpectedly large scalar type");
3913
3914 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3915
3916 // If the type may need padding registers to ensure "alignment", we must be
3917 // careful when this is accounted for. Increasing the effective size covers
3918 // all cases.
3919 if (getContext().getTypeAlign(Ty) == 128)
3920 RegsNeeded += FreeIntRegs % 2 != 0;
3921
3922 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3923 }
3924
Mark Lacey3825e832013-10-06 01:33:34 +00003925 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003926 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00003927 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003928 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00003929 }
3930
3931 if (isEmptyRecord(getContext(), Ty, true)) {
3932 if (!getContext().getLangOpts().CPlusPlus) {
3933 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3934 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3935 // the object for parameter-passsing purposes.
3936 return ABIArgInfo::getIgnore();
3937 }
3938
3939 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3940 // description of va_arg in the PCS require that an empty struct does
3941 // actually occupy space for parameter-passing. I'm hoping for a
3942 // clarification giving an explicit paragraph to point to in future.
3943 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3944 llvm::Type::getInt8Ty(getVMContext()));
3945 }
3946
3947 // Homogeneous vector aggregates get passed in registers or on the stack.
3948 const Type *Base = 0;
3949 uint64_t NumMembers = 0;
3950 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3951 assert(Base && "Base class should be set for homogeneous aggregate");
3952 // Homogeneous aggregates are passed and returned directly.
3953 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3954 /*IsInt=*/ false);
3955 }
3956
3957 uint64_t Size = getContext().getTypeSize(Ty);
3958 if (Size <= 128) {
3959 // Small structs can use the same direct type whether they're in registers
3960 // or on the stack.
3961 llvm::Type *BaseTy;
3962 unsigned NumBases;
3963 int SizeInRegs = (Size + 63) / 64;
3964
3965 if (getContext().getTypeAlign(Ty) == 128) {
3966 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3967 NumBases = 1;
3968
3969 // If the type may need padding registers to ensure "alignment", we must
3970 // be careful when this is accounted for. Increasing the effective size
3971 // covers all cases.
3972 SizeInRegs += FreeIntRegs % 2 != 0;
3973 } else {
3974 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3975 NumBases = SizeInRegs;
3976 }
3977 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3978
3979 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3980 /*IsInt=*/ true, DirectTy);
3981 }
3982
3983 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3984 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3985 --FreeIntRegs;
3986 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3987}
3988
3989llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3990 CodeGenFunction &CGF) const {
3991 // The AArch64 va_list type and handling is specified in the Procedure Call
3992 // Standard, section B.4:
3993 //
3994 // struct {
3995 // void *__stack;
3996 // void *__gr_top;
3997 // void *__vr_top;
3998 // int __gr_offs;
3999 // int __vr_offs;
4000 // };
4001
4002 assert(!CGF.CGM.getDataLayout().isBigEndian()
4003 && "va_arg not implemented for big-endian AArch64");
4004
4005 int FreeIntRegs = 8, FreeVFPRegs = 8;
4006 Ty = CGF.getContext().getCanonicalType(Ty);
4007 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4008
4009 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4010 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4011 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4012 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4013
4014 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4015 int reg_top_index;
4016 int RegSize;
4017 if (FreeIntRegs < 8) {
4018 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4019 // 3 is the field number of __gr_offs
4020 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4021 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4022 reg_top_index = 1; // field number for __gr_top
4023 RegSize = 8 * (8 - FreeIntRegs);
4024 } else {
4025 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4026 // 4 is the field number of __vr_offs.
4027 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4028 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4029 reg_top_index = 2; // field number for __vr_top
4030 RegSize = 16 * (8 - FreeVFPRegs);
4031 }
4032
4033 //=======================================
4034 // Find out where argument was passed
4035 //=======================================
4036
4037 // If reg_offs >= 0 we're already using the stack for this type of
4038 // argument. We don't want to keep updating reg_offs (in case it overflows,
4039 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4040 // whatever they get).
4041 llvm::Value *UsingStack = 0;
4042 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4043 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4044
4045 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4046
4047 // Otherwise, at least some kind of argument could go in these registers, the
4048 // quesiton is whether this particular type is too big.
4049 CGF.EmitBlock(MaybeRegBlock);
4050
4051 // Integer arguments may need to correct register alignment (for example a
4052 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4053 // align __gr_offs to calculate the potential address.
4054 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4055 int Align = getContext().getTypeAlign(Ty) / 8;
4056
4057 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4058 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4059 "align_regoffs");
4060 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4061 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4062 "aligned_regoffs");
4063 }
4064
4065 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4066 llvm::Value *NewOffset = 0;
4067 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4068 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4069 "new_reg_offs");
4070 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4071
4072 // Now we're in a position to decide whether this argument really was in
4073 // registers or not.
4074 llvm::Value *InRegs = 0;
4075 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4076 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4077 "inreg");
4078
4079 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4080
4081 //=======================================
4082 // Argument was in registers
4083 //=======================================
4084
4085 // Now we emit the code for if the argument was originally passed in
4086 // registers. First start the appropriate block:
4087 CGF.EmitBlock(InRegBlock);
4088
4089 llvm::Value *reg_top_p = 0, *reg_top = 0;
4090 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4091 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4092 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4093 llvm::Value *RegAddr = 0;
4094 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4095
4096 if (!AI.isDirect()) {
4097 // If it's been passed indirectly (actually a struct), whatever we find from
4098 // stored registers or on the stack will actually be a struct **.
4099 MemTy = llvm::PointerType::getUnqual(MemTy);
4100 }
4101
4102 const Type *Base = 0;
4103 uint64_t NumMembers;
4104 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4105 && NumMembers > 1) {
4106 // Homogeneous aggregates passed in registers will have their elements split
4107 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4108 // qN+1, ...). We reload and store into a temporary local variable
4109 // contiguously.
4110 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4111 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4112 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4113 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4114
4115 for (unsigned i = 0; i < NumMembers; ++i) {
4116 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4117 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4118 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4119 llvm::PointerType::getUnqual(BaseTy));
4120 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4121
4122 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4123 CGF.Builder.CreateStore(Elem, StoreAddr);
4124 }
4125
4126 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4127 } else {
4128 // Otherwise the object is contiguous in memory
4129 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4130 }
4131
4132 CGF.EmitBranch(ContBlock);
4133
4134 //=======================================
4135 // Argument was on the stack
4136 //=======================================
4137 CGF.EmitBlock(OnStackBlock);
4138
4139 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4140 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4141 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4142
4143 // Again, stack arguments may need realigmnent. In this case both integer and
4144 // floating-point ones might be affected.
4145 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4146 int Align = getContext().getTypeAlign(Ty) / 8;
4147
4148 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4149
4150 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4151 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4152 "align_stack");
4153 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4154 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4155 "align_stack");
4156
4157 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4158 }
4159
4160 uint64_t StackSize;
4161 if (AI.isDirect())
4162 StackSize = getContext().getTypeSize(Ty) / 8;
4163 else
4164 StackSize = 8;
4165
4166 // All stack slots are 8 bytes
4167 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4168
4169 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4170 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4171 "new_stack");
4172
4173 // Write the new value of __stack for the next call to va_arg
4174 CGF.Builder.CreateStore(NewStack, stack_p);
4175
4176 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4177
4178 CGF.EmitBranch(ContBlock);
4179
4180 //=======================================
4181 // Tidy up
4182 //=======================================
4183 CGF.EmitBlock(ContBlock);
4184
4185 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4186 ResAddr->addIncoming(RegAddr, InRegBlock);
4187 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4188
4189 if (AI.isDirect())
4190 return ResAddr;
4191
4192 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4193}
4194
4195//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004196// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004197//===----------------------------------------------------------------------===//
4198
4199namespace {
4200
Justin Holewinski83e96682012-05-24 17:43:12 +00004201class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004202public:
Justin Holewinski36837432013-03-30 14:38:24 +00004203 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004204
4205 ABIArgInfo classifyReturnType(QualType RetTy) const;
4206 ABIArgInfo classifyArgumentType(QualType Ty) const;
4207
4208 virtual void computeInfo(CGFunctionInfo &FI) const;
4209 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4210 CodeGenFunction &CFG) const;
4211};
4212
Justin Holewinski83e96682012-05-24 17:43:12 +00004213class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004214public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004215 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4216 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski38031972011-10-05 17:58:44 +00004217
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004218 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4219 CodeGen::CodeGenModule &M) const;
Justin Holewinski36837432013-03-30 14:38:24 +00004220private:
4221 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004222};
4223
Justin Holewinski83e96682012-05-24 17:43:12 +00004224ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004225 if (RetTy->isVoidType())
4226 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004227
4228 // note: this is different from default ABI
4229 if (!RetTy->isScalarType())
4230 return ABIArgInfo::getDirect();
4231
4232 // Treat an enum type as its underlying type.
4233 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4234 RetTy = EnumTy->getDecl()->getIntegerType();
4235
4236 return (RetTy->isPromotableIntegerType() ?
4237 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004238}
4239
Justin Holewinski83e96682012-05-24 17:43:12 +00004240ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004241 // Treat an enum type as its underlying type.
4242 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4243 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004244
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004245 return (Ty->isPromotableIntegerType() ?
4246 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004247}
4248
Justin Holewinski83e96682012-05-24 17:43:12 +00004249void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004250 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4251 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4252 it != ie; ++it)
4253 it->info = classifyArgumentType(it->type);
4254
4255 // Always honor user-specified calling convention.
4256 if (FI.getCallingConvention() != llvm::CallingConv::C)
4257 return;
4258
John McCall882987f2013-02-28 19:01:20 +00004259 FI.setEffectiveCallingConvention(getRuntimeCC());
4260}
4261
Justin Holewinski83e96682012-05-24 17:43:12 +00004262llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4263 CodeGenFunction &CFG) const {
4264 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004265}
4266
Justin Holewinski83e96682012-05-24 17:43:12 +00004267void NVPTXTargetCodeGenInfo::
4268SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4269 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004270 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4271 if (!FD) return;
4272
4273 llvm::Function *F = cast<llvm::Function>(GV);
4274
4275 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004276 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004277 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004278 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004279 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004280 // OpenCL __kernel functions get kernel metadata
4281 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004282 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004283 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004284 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004285 }
Justin Holewinski38031972011-10-05 17:58:44 +00004286
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004287 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004288 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004289 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004290 // __global__ functions cannot be called from the device, we do not
4291 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004292 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004293 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004294 }
4295}
4296
Justin Holewinski36837432013-03-30 14:38:24 +00004297void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4298 llvm::Module *M = F->getParent();
4299 llvm::LLVMContext &Ctx = M->getContext();
4300
4301 // Get "nvvm.annotations" metadata node
4302 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4303
4304 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4305 llvm::SmallVector<llvm::Value *, 3> MDVals;
4306 MDVals.push_back(F);
4307 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4308 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4309
4310 // Append metadata to nvvm.annotations
4311 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4312}
4313
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004314}
4315
4316//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004317// SystemZ ABI Implementation
4318//===----------------------------------------------------------------------===//
4319
4320namespace {
4321
4322class SystemZABIInfo : public ABIInfo {
4323public:
4324 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4325
4326 bool isPromotableIntegerType(QualType Ty) const;
4327 bool isCompoundType(QualType Ty) const;
4328 bool isFPArgumentType(QualType Ty) const;
4329
4330 ABIArgInfo classifyReturnType(QualType RetTy) const;
4331 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4332
4333 virtual void computeInfo(CGFunctionInfo &FI) const {
4334 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4335 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4336 it != ie; ++it)
4337 it->info = classifyArgumentType(it->type);
4338 }
4339
4340 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4341 CodeGenFunction &CGF) const;
4342};
4343
4344class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4345public:
4346 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4347 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4348};
4349
4350}
4351
4352bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4353 // Treat an enum type as its underlying type.
4354 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4355 Ty = EnumTy->getDecl()->getIntegerType();
4356
4357 // Promotable integer types are required to be promoted by the ABI.
4358 if (Ty->isPromotableIntegerType())
4359 return true;
4360
4361 // 32-bit values must also be promoted.
4362 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4363 switch (BT->getKind()) {
4364 case BuiltinType::Int:
4365 case BuiltinType::UInt:
4366 return true;
4367 default:
4368 return false;
4369 }
4370 return false;
4371}
4372
4373bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4374 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4375}
4376
4377bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4378 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4379 switch (BT->getKind()) {
4380 case BuiltinType::Float:
4381 case BuiltinType::Double:
4382 return true;
4383 default:
4384 return false;
4385 }
4386
4387 if (const RecordType *RT = Ty->getAsStructureType()) {
4388 const RecordDecl *RD = RT->getDecl();
4389 bool Found = false;
4390
4391 // If this is a C++ record, check the bases first.
4392 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4393 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4394 E = CXXRD->bases_end(); I != E; ++I) {
4395 QualType Base = I->getType();
4396
4397 // Empty bases don't affect things either way.
4398 if (isEmptyRecord(getContext(), Base, true))
4399 continue;
4400
4401 if (Found)
4402 return false;
4403 Found = isFPArgumentType(Base);
4404 if (!Found)
4405 return false;
4406 }
4407
4408 // Check the fields.
4409 for (RecordDecl::field_iterator I = RD->field_begin(),
4410 E = RD->field_end(); I != E; ++I) {
4411 const FieldDecl *FD = *I;
4412
4413 // Empty bitfields don't affect things either way.
4414 // Unlike isSingleElementStruct(), empty structure and array fields
4415 // do count. So do anonymous bitfields that aren't zero-sized.
4416 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4417 return true;
4418
4419 // Unlike isSingleElementStruct(), arrays do not count.
4420 // Nested isFPArgumentType structures still do though.
4421 if (Found)
4422 return false;
4423 Found = isFPArgumentType(FD->getType());
4424 if (!Found)
4425 return false;
4426 }
4427
4428 // Unlike isSingleElementStruct(), trailing padding is allowed.
4429 // An 8-byte aligned struct s { float f; } is passed as a double.
4430 return Found;
4431 }
4432
4433 return false;
4434}
4435
4436llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4437 CodeGenFunction &CGF) const {
4438 // Assume that va_list type is correct; should be pointer to LLVM type:
4439 // struct {
4440 // i64 __gpr;
4441 // i64 __fpr;
4442 // i8 *__overflow_arg_area;
4443 // i8 *__reg_save_area;
4444 // };
4445
4446 // Every argument occupies 8 bytes and is passed by preference in either
4447 // GPRs or FPRs.
4448 Ty = CGF.getContext().getCanonicalType(Ty);
4449 ABIArgInfo AI = classifyArgumentType(Ty);
4450 bool InFPRs = isFPArgumentType(Ty);
4451
4452 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4453 bool IsIndirect = AI.isIndirect();
4454 unsigned UnpaddedBitSize;
4455 if (IsIndirect) {
4456 APTy = llvm::PointerType::getUnqual(APTy);
4457 UnpaddedBitSize = 64;
4458 } else
4459 UnpaddedBitSize = getContext().getTypeSize(Ty);
4460 unsigned PaddedBitSize = 64;
4461 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4462
4463 unsigned PaddedSize = PaddedBitSize / 8;
4464 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4465
4466 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4467 if (InFPRs) {
4468 MaxRegs = 4; // Maximum of 4 FPR arguments
4469 RegCountField = 1; // __fpr
4470 RegSaveIndex = 16; // save offset for f0
4471 RegPadding = 0; // floats are passed in the high bits of an FPR
4472 } else {
4473 MaxRegs = 5; // Maximum of 5 GPR arguments
4474 RegCountField = 0; // __gpr
4475 RegSaveIndex = 2; // save offset for r2
4476 RegPadding = Padding; // values are passed in the low bits of a GPR
4477 }
4478
4479 llvm::Value *RegCountPtr =
4480 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4481 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4482 llvm::Type *IndexTy = RegCount->getType();
4483 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4484 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4485 "fits_in_regs");
4486
4487 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4488 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4489 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4490 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4491
4492 // Emit code to load the value if it was passed in registers.
4493 CGF.EmitBlock(InRegBlock);
4494
4495 // Work out the address of an argument register.
4496 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4497 llvm::Value *ScaledRegCount =
4498 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4499 llvm::Value *RegBase =
4500 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4501 llvm::Value *RegOffset =
4502 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4503 llvm::Value *RegSaveAreaPtr =
4504 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4505 llvm::Value *RegSaveArea =
4506 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4507 llvm::Value *RawRegAddr =
4508 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4509 llvm::Value *RegAddr =
4510 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4511
4512 // Update the register count
4513 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4514 llvm::Value *NewRegCount =
4515 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4516 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4517 CGF.EmitBranch(ContBlock);
4518
4519 // Emit code to load the value if it was passed in memory.
4520 CGF.EmitBlock(InMemBlock);
4521
4522 // Work out the address of a stack argument.
4523 llvm::Value *OverflowArgAreaPtr =
4524 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4525 llvm::Value *OverflowArgArea =
4526 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4527 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4528 llvm::Value *RawMemAddr =
4529 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4530 llvm::Value *MemAddr =
4531 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4532
4533 // Update overflow_arg_area_ptr pointer
4534 llvm::Value *NewOverflowArgArea =
4535 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4536 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4537 CGF.EmitBranch(ContBlock);
4538
4539 // Return the appropriate result.
4540 CGF.EmitBlock(ContBlock);
4541 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4542 ResAddr->addIncoming(RegAddr, InRegBlock);
4543 ResAddr->addIncoming(MemAddr, InMemBlock);
4544
4545 if (IsIndirect)
4546 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4547
4548 return ResAddr;
4549}
4550
John McCall1fe2a8c2013-06-18 02:46:29 +00004551bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4552 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4553 assert(Triple.getArch() == llvm::Triple::x86);
4554
4555 switch (Opts.getStructReturnConvention()) {
4556 case CodeGenOptions::SRCK_Default:
4557 break;
4558 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4559 return false;
4560 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4561 return true;
4562 }
4563
4564 if (Triple.isOSDarwin())
4565 return true;
4566
4567 switch (Triple.getOS()) {
4568 case llvm::Triple::Cygwin:
4569 case llvm::Triple::MinGW32:
4570 case llvm::Triple::AuroraUX:
4571 case llvm::Triple::DragonFly:
4572 case llvm::Triple::FreeBSD:
4573 case llvm::Triple::OpenBSD:
4574 case llvm::Triple::Bitrig:
4575 case llvm::Triple::Win32:
4576 return true;
4577 default:
4578 return false;
4579 }
4580}
Ulrich Weigand47445072013-05-06 16:26:41 +00004581
4582ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4583 if (RetTy->isVoidType())
4584 return ABIArgInfo::getIgnore();
4585 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4586 return ABIArgInfo::getIndirect(0);
4587 return (isPromotableIntegerType(RetTy) ?
4588 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4589}
4590
4591ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4592 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004593 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004594 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4595
4596 // Integers and enums are extended to full register width.
4597 if (isPromotableIntegerType(Ty))
4598 return ABIArgInfo::getExtend();
4599
4600 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4601 uint64_t Size = getContext().getTypeSize(Ty);
4602 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004603 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004604
4605 // Handle small structures.
4606 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4607 // Structures with flexible arrays have variable length, so really
4608 // fail the size test above.
4609 const RecordDecl *RD = RT->getDecl();
4610 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004611 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004612
4613 // The structure is passed as an unextended integer, a float, or a double.
4614 llvm::Type *PassTy;
4615 if (isFPArgumentType(Ty)) {
4616 assert(Size == 32 || Size == 64);
4617 if (Size == 32)
4618 PassTy = llvm::Type::getFloatTy(getVMContext());
4619 else
4620 PassTy = llvm::Type::getDoubleTy(getVMContext());
4621 } else
4622 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4623 return ABIArgInfo::getDirect(PassTy);
4624 }
4625
4626 // Non-structure compounds are passed indirectly.
4627 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004628 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004629
4630 return ABIArgInfo::getDirect(0);
4631}
4632
4633//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004634// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004635//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004636
4637namespace {
4638
4639class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4640public:
Chris Lattner2b037972010-07-29 02:01:43 +00004641 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4642 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004643 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4644 CodeGen::CodeGenModule &M) const;
4645};
4646
4647}
4648
4649void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4650 llvm::GlobalValue *GV,
4651 CodeGen::CodeGenModule &M) const {
4652 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4653 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4654 // Handle 'interrupt' attribute:
4655 llvm::Function *F = cast<llvm::Function>(GV);
4656
4657 // Step 1: Set ISR calling convention.
4658 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4659
4660 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004661 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004662
4663 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004664 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004665 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004666 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004667 GV, &M.getModule());
4668 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004669 }
4670}
4671
Chris Lattner0cf24192010-06-28 20:05:43 +00004672//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004673// MIPS ABI Implementation. This works for both little-endian and
4674// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004675//===----------------------------------------------------------------------===//
4676
John McCall943fae92010-05-27 06:19:26 +00004677namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004678class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004679 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004680 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4681 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004682 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004683 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004684 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004685 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004686public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004687 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004688 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004689 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004690
4691 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004692 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004693 virtual void computeInfo(CGFunctionInfo &FI) const;
4694 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4695 CodeGenFunction &CGF) const;
4696};
4697
John McCall943fae92010-05-27 06:19:26 +00004698class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004699 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004700public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004701 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4702 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004703 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004704
4705 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4706 return 29;
4707 }
4708
Reed Kotler373feca2013-01-16 17:10:28 +00004709 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4710 CodeGen::CodeGenModule &CGM) const {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004711 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4712 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004713 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004714 if (FD->hasAttr<Mips16Attr>()) {
4715 Fn->addFnAttr("mips16");
4716 }
4717 else if (FD->hasAttr<NoMips16Attr>()) {
4718 Fn->addFnAttr("nomips16");
4719 }
Reed Kotler373feca2013-01-16 17:10:28 +00004720 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004721
John McCall943fae92010-05-27 06:19:26 +00004722 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004723 llvm::Value *Address) const;
John McCall3480ef22011-08-30 01:42:09 +00004724
4725 unsigned getSizeOfUnwindException() const {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004726 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004727 }
John McCall943fae92010-05-27 06:19:26 +00004728};
4729}
4730
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004731void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004732 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004733 llvm::IntegerType *IntTy =
4734 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004735
4736 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4737 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4738 ArgList.push_back(IntTy);
4739
4740 // If necessary, add one more integer type to ArgList.
4741 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4742
4743 if (R)
4744 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004745}
4746
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004747// In N32/64, an aligned double precision floating point field is passed in
4748// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004749llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004750 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4751
4752 if (IsO32) {
4753 CoerceToIntArgs(TySize, ArgList);
4754 return llvm::StructType::get(getVMContext(), ArgList);
4755 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004756
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004757 if (Ty->isComplexType())
4758 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004759
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004760 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004761
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004762 // Unions/vectors are passed in integer registers.
4763 if (!RT || !RT->isStructureOrClassType()) {
4764 CoerceToIntArgs(TySize, ArgList);
4765 return llvm::StructType::get(getVMContext(), ArgList);
4766 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004767
4768 const RecordDecl *RD = RT->getDecl();
4769 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004770 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004771
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004772 uint64_t LastOffset = 0;
4773 unsigned idx = 0;
4774 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4775
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004776 // Iterate over fields in the struct/class and check if there are any aligned
4777 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004778 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4779 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004780 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004781 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4782
4783 if (!BT || BT->getKind() != BuiltinType::Double)
4784 continue;
4785
4786 uint64_t Offset = Layout.getFieldOffset(idx);
4787 if (Offset % 64) // Ignore doubles that are not aligned.
4788 continue;
4789
4790 // Add ((Offset - LastOffset) / 64) args of type i64.
4791 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4792 ArgList.push_back(I64);
4793
4794 // Add double type.
4795 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4796 LastOffset = Offset + 64;
4797 }
4798
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004799 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4800 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004801
4802 return llvm::StructType::get(getVMContext(), ArgList);
4803}
4804
Akira Hatanakaddd66342013-10-29 18:41:15 +00004805llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4806 uint64_t Offset) const {
4807 if (OrigOffset + MinABIStackAlignInBytes > Offset)
4808 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004809
Akira Hatanakaddd66342013-10-29 18:41:15 +00004810 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004811}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00004812
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004813ABIArgInfo
4814MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00004815 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004816 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004817 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004818
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004819 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4820 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00004821 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4822 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004823
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004824 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004825 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004826 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004827 return ABIArgInfo::getIgnore();
4828
Mark Lacey3825e832013-10-06 01:33:34 +00004829 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004830 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004831 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004832 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00004833
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004834 // If we have reached here, aggregates are passed directly by coercing to
4835 // another structure type. Padding is inserted if the offset of the
4836 // aggregate is unaligned.
4837 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00004838 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004839 }
4840
4841 // Treat an enum type as its underlying type.
4842 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4843 Ty = EnumTy->getDecl()->getIntegerType();
4844
Akira Hatanaka1632af62012-01-09 19:31:25 +00004845 if (Ty->isPromotableIntegerType())
4846 return ABIArgInfo::getExtend();
4847
Akira Hatanakaddd66342013-10-29 18:41:15 +00004848 return ABIArgInfo::getDirect(
4849 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004850}
4851
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004852llvm::Type*
4853MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00004854 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004855 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004856
Akira Hatanakab6f74432012-02-09 18:49:26 +00004857 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004858 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00004859 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4860 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004861
Akira Hatanakab6f74432012-02-09 18:49:26 +00004862 // N32/64 returns struct/classes in floating point registers if the
4863 // following conditions are met:
4864 // 1. The size of the struct/class is no larger than 128-bit.
4865 // 2. The struct/class has one or two fields all of which are floating
4866 // point types.
4867 // 3. The offset of the first field is zero (this follows what gcc does).
4868 //
4869 // Any other composite results are returned in integer registers.
4870 //
4871 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4872 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4873 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004874 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004875
Akira Hatanakab6f74432012-02-09 18:49:26 +00004876 if (!BT || !BT->isFloatingPoint())
4877 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004878
David Blaikie2d7c57e2012-04-30 02:36:29 +00004879 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00004880 }
4881
4882 if (b == e)
4883 return llvm::StructType::get(getVMContext(), RTList,
4884 RD->hasAttr<PackedAttr>());
4885
4886 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004887 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004888 }
4889
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004890 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004891 return llvm::StructType::get(getVMContext(), RTList);
4892}
4893
Akira Hatanakab579fe52011-06-02 00:09:17 +00004894ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00004895 uint64_t Size = getContext().getTypeSize(RetTy);
4896
4897 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004898 return ABIArgInfo::getIgnore();
4899
Akira Hatanakac37eddf2012-05-11 21:01:17 +00004900 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00004901 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004902 return ABIArgInfo::getIndirect(0);
4903
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004904 if (Size <= 128) {
4905 if (RetTy->isAnyComplexType())
4906 return ABIArgInfo::getDirect();
4907
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004908 // O32 returns integer vectors in registers.
4909 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4910 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4911
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004912 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004913 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4914 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00004915
4916 return ABIArgInfo::getIndirect(0);
4917 }
4918
4919 // Treat an enum type as its underlying type.
4920 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4921 RetTy = EnumTy->getDecl()->getIntegerType();
4922
4923 return (RetTy->isPromotableIntegerType() ?
4924 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4925}
4926
4927void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00004928 ABIArgInfo &RetInfo = FI.getReturnInfo();
4929 RetInfo = classifyReturnType(FI.getReturnType());
4930
4931 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004932 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00004933
Akira Hatanakab579fe52011-06-02 00:09:17 +00004934 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4935 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004936 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00004937}
4938
4939llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4940 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004941 llvm::Type *BP = CGF.Int8PtrTy;
4942 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004943
4944 CGBuilderTy &Builder = CGF.Builder;
4945 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4946 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00004947 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004948 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4949 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00004950 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00004951 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004952
4953 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00004954 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4955 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4956 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4957 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004958 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4959 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4960 }
4961 else
4962 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4963
4964 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00004965 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004966 uint64_t Offset =
4967 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4968 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00004969 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004970 "ap.next");
4971 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4972
4973 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004974}
4975
John McCall943fae92010-05-27 06:19:26 +00004976bool
4977MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4978 llvm::Value *Address) const {
4979 // This information comes from gcc's implementation, which seems to
4980 // as canonical as it gets.
4981
John McCall943fae92010-05-27 06:19:26 +00004982 // Everything on MIPS is 4 bytes. Double-precision FP registers
4983 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004984 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00004985
4986 // 0-31 are the general purpose registers, $0 - $31.
4987 // 32-63 are the floating-point registers, $f0 - $f31.
4988 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4989 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00004990 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00004991
4992 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4993 // They are one bit wide and ignored here.
4994
4995 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4996 // (coprocessor 1 is the FP unit)
4997 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4998 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4999 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005000 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005001 return false;
5002}
5003
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005004//===----------------------------------------------------------------------===//
5005// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5006// Currently subclassed only to implement custom OpenCL C function attribute
5007// handling.
5008//===----------------------------------------------------------------------===//
5009
5010namespace {
5011
5012class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5013public:
5014 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5015 : DefaultTargetCodeGenInfo(CGT) {}
5016
5017 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5018 CodeGen::CodeGenModule &M) const;
5019};
5020
5021void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5022 llvm::GlobalValue *GV,
5023 CodeGen::CodeGenModule &M) const {
5024 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5025 if (!FD) return;
5026
5027 llvm::Function *F = cast<llvm::Function>(GV);
5028
David Blaikiebbafb8a2012-03-11 07:00:24 +00005029 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005030 if (FD->hasAttr<OpenCLKernelAttr>()) {
5031 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005032 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005033 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5034 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005035 // Convert the reqd_work_group_size() attributes to metadata.
5036 llvm::LLVMContext &Context = F->getContext();
5037 llvm::NamedMDNode *OpenCLMetadata =
5038 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5039
5040 SmallVector<llvm::Value*, 5> Operands;
5041 Operands.push_back(F);
5042
Chris Lattnerece04092012-02-07 00:39:47 +00005043 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005044 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005045 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005046 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005047 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005048 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005049
5050 // Add a boolean constant operand for "required" (true) or "hint" (false)
5051 // for implementing the work_group_size_hint attr later. Currently
5052 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005053 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005054 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5055 }
5056 }
5057 }
5058}
5059
5060}
John McCall943fae92010-05-27 06:19:26 +00005061
Tony Linthicum76329bf2011-12-12 21:14:55 +00005062//===----------------------------------------------------------------------===//
5063// Hexagon ABI Implementation
5064//===----------------------------------------------------------------------===//
5065
5066namespace {
5067
5068class HexagonABIInfo : public ABIInfo {
5069
5070
5071public:
5072 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5073
5074private:
5075
5076 ABIArgInfo classifyReturnType(QualType RetTy) const;
5077 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5078
5079 virtual void computeInfo(CGFunctionInfo &FI) const;
5080
5081 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5082 CodeGenFunction &CGF) const;
5083};
5084
5085class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5086public:
5087 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5088 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5089
5090 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5091 return 29;
5092 }
5093};
5094
5095}
5096
5097void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5098 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5099 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5100 it != ie; ++it)
5101 it->info = classifyArgumentType(it->type);
5102}
5103
5104ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5105 if (!isAggregateTypeForABI(Ty)) {
5106 // Treat an enum type as its underlying type.
5107 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5108 Ty = EnumTy->getDecl()->getIntegerType();
5109
5110 return (Ty->isPromotableIntegerType() ?
5111 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5112 }
5113
5114 // Ignore empty records.
5115 if (isEmptyRecord(getContext(), Ty, true))
5116 return ABIArgInfo::getIgnore();
5117
Mark Lacey3825e832013-10-06 01:33:34 +00005118 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005119 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005120
5121 uint64_t Size = getContext().getTypeSize(Ty);
5122 if (Size > 64)
5123 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5124 // Pass in the smallest viable integer type.
5125 else if (Size > 32)
5126 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5127 else if (Size > 16)
5128 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5129 else if (Size > 8)
5130 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5131 else
5132 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5133}
5134
5135ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5136 if (RetTy->isVoidType())
5137 return ABIArgInfo::getIgnore();
5138
5139 // Large vector types should be returned via memory.
5140 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5141 return ABIArgInfo::getIndirect(0);
5142
5143 if (!isAggregateTypeForABI(RetTy)) {
5144 // Treat an enum type as its underlying type.
5145 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5146 RetTy = EnumTy->getDecl()->getIntegerType();
5147
5148 return (RetTy->isPromotableIntegerType() ?
5149 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5150 }
5151
5152 // Structures with either a non-trivial destructor or a non-trivial
5153 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005154 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005155 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5156
5157 if (isEmptyRecord(getContext(), RetTy, true))
5158 return ABIArgInfo::getIgnore();
5159
5160 // Aggregates <= 8 bytes are returned in r0; other aggregates
5161 // are returned indirectly.
5162 uint64_t Size = getContext().getTypeSize(RetTy);
5163 if (Size <= 64) {
5164 // Return in the smallest viable integer type.
5165 if (Size <= 8)
5166 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5167 if (Size <= 16)
5168 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5169 if (Size <= 32)
5170 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5171 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5172 }
5173
5174 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5175}
5176
5177llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005178 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005179 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005180 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005181
5182 CGBuilderTy &Builder = CGF.Builder;
5183 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5184 "ap");
5185 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5186 llvm::Type *PTy =
5187 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5188 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5189
5190 uint64_t Offset =
5191 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5192 llvm::Value *NextAddr =
5193 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5194 "ap.next");
5195 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5196
5197 return AddrTyped;
5198}
5199
5200
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005201//===----------------------------------------------------------------------===//
5202// SPARC v9 ABI Implementation.
5203// Based on the SPARC Compliance Definition version 2.4.1.
5204//
5205// Function arguments a mapped to a nominal "parameter array" and promoted to
5206// registers depending on their type. Each argument occupies 8 or 16 bytes in
5207// the array, structs larger than 16 bytes are passed indirectly.
5208//
5209// One case requires special care:
5210//
5211// struct mixed {
5212// int i;
5213// float f;
5214// };
5215//
5216// When a struct mixed is passed by value, it only occupies 8 bytes in the
5217// parameter array, but the int is passed in an integer register, and the float
5218// is passed in a floating point register. This is represented as two arguments
5219// with the LLVM IR inreg attribute:
5220//
5221// declare void f(i32 inreg %i, float inreg %f)
5222//
5223// The code generator will only allocate 4 bytes from the parameter array for
5224// the inreg arguments. All other arguments are allocated a multiple of 8
5225// bytes.
5226//
5227namespace {
5228class SparcV9ABIInfo : public ABIInfo {
5229public:
5230 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5231
5232private:
5233 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5234 virtual void computeInfo(CGFunctionInfo &FI) const;
5235 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5236 CodeGenFunction &CGF) const;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005237
5238 // Coercion type builder for structs passed in registers. The coercion type
5239 // serves two purposes:
5240 //
5241 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5242 // in registers.
5243 // 2. Expose aligned floating point elements as first-level elements, so the
5244 // code generator knows to pass them in floating point registers.
5245 //
5246 // We also compute the InReg flag which indicates that the struct contains
5247 // aligned 32-bit floats.
5248 //
5249 struct CoerceBuilder {
5250 llvm::LLVMContext &Context;
5251 const llvm::DataLayout &DL;
5252 SmallVector<llvm::Type*, 8> Elems;
5253 uint64_t Size;
5254 bool InReg;
5255
5256 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5257 : Context(c), DL(dl), Size(0), InReg(false) {}
5258
5259 // Pad Elems with integers until Size is ToSize.
5260 void pad(uint64_t ToSize) {
5261 assert(ToSize >= Size && "Cannot remove elements");
5262 if (ToSize == Size)
5263 return;
5264
5265 // Finish the current 64-bit word.
5266 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5267 if (Aligned > Size && Aligned <= ToSize) {
5268 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5269 Size = Aligned;
5270 }
5271
5272 // Add whole 64-bit words.
5273 while (Size + 64 <= ToSize) {
5274 Elems.push_back(llvm::Type::getInt64Ty(Context));
5275 Size += 64;
5276 }
5277
5278 // Final in-word padding.
5279 if (Size < ToSize) {
5280 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5281 Size = ToSize;
5282 }
5283 }
5284
5285 // Add a floating point element at Offset.
5286 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5287 // Unaligned floats are treated as integers.
5288 if (Offset % Bits)
5289 return;
5290 // The InReg flag is only required if there are any floats < 64 bits.
5291 if (Bits < 64)
5292 InReg = true;
5293 pad(Offset);
5294 Elems.push_back(Ty);
5295 Size = Offset + Bits;
5296 }
5297
5298 // Add a struct type to the coercion type, starting at Offset (in bits).
5299 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5300 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5301 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5302 llvm::Type *ElemTy = StrTy->getElementType(i);
5303 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5304 switch (ElemTy->getTypeID()) {
5305 case llvm::Type::StructTyID:
5306 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5307 break;
5308 case llvm::Type::FloatTyID:
5309 addFloat(ElemOffset, ElemTy, 32);
5310 break;
5311 case llvm::Type::DoubleTyID:
5312 addFloat(ElemOffset, ElemTy, 64);
5313 break;
5314 case llvm::Type::FP128TyID:
5315 addFloat(ElemOffset, ElemTy, 128);
5316 break;
5317 case llvm::Type::PointerTyID:
5318 if (ElemOffset % 64 == 0) {
5319 pad(ElemOffset);
5320 Elems.push_back(ElemTy);
5321 Size += 64;
5322 }
5323 break;
5324 default:
5325 break;
5326 }
5327 }
5328 }
5329
5330 // Check if Ty is a usable substitute for the coercion type.
5331 bool isUsableType(llvm::StructType *Ty) const {
5332 if (Ty->getNumElements() != Elems.size())
5333 return false;
5334 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5335 if (Elems[i] != Ty->getElementType(i))
5336 return false;
5337 return true;
5338 }
5339
5340 // Get the coercion type as a literal struct type.
5341 llvm::Type *getType() const {
5342 if (Elems.size() == 1)
5343 return Elems.front();
5344 else
5345 return llvm::StructType::get(Context, Elems);
5346 }
5347 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005348};
5349} // end anonymous namespace
5350
5351ABIArgInfo
5352SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5353 if (Ty->isVoidType())
5354 return ABIArgInfo::getIgnore();
5355
5356 uint64_t Size = getContext().getTypeSize(Ty);
5357
5358 // Anything too big to fit in registers is passed with an explicit indirect
5359 // pointer / sret pointer.
5360 if (Size > SizeLimit)
5361 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5362
5363 // Treat an enum type as its underlying type.
5364 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5365 Ty = EnumTy->getDecl()->getIntegerType();
5366
5367 // Integer types smaller than a register are extended.
5368 if (Size < 64 && Ty->isIntegerType())
5369 return ABIArgInfo::getExtend();
5370
5371 // Other non-aggregates go in registers.
5372 if (!isAggregateTypeForABI(Ty))
5373 return ABIArgInfo::getDirect();
5374
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005375 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5376 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5377 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5378 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5379
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005380 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005381 // Build a coercion type from the LLVM struct type.
5382 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5383 if (!StrTy)
5384 return ABIArgInfo::getDirect();
5385
5386 CoerceBuilder CB(getVMContext(), getDataLayout());
5387 CB.addStruct(0, StrTy);
5388 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5389
5390 // Try to use the original type for coercion.
5391 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5392
5393 if (CB.InReg)
5394 return ABIArgInfo::getDirectInReg(CoerceTy);
5395 else
5396 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005397}
5398
5399llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5400 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005401 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5402 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5403 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5404 AI.setCoerceToType(ArgTy);
5405
5406 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5407 CGBuilderTy &Builder = CGF.Builder;
5408 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5409 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5410 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5411 llvm::Value *ArgAddr;
5412 unsigned Stride;
5413
5414 switch (AI.getKind()) {
5415 case ABIArgInfo::Expand:
5416 llvm_unreachable("Unsupported ABI kind for va_arg");
5417
5418 case ABIArgInfo::Extend:
5419 Stride = 8;
5420 ArgAddr = Builder
5421 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5422 "extend");
5423 break;
5424
5425 case ABIArgInfo::Direct:
5426 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5427 ArgAddr = Addr;
5428 break;
5429
5430 case ABIArgInfo::Indirect:
5431 Stride = 8;
5432 ArgAddr = Builder.CreateBitCast(Addr,
5433 llvm::PointerType::getUnqual(ArgPtrTy),
5434 "indirect");
5435 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5436 break;
5437
5438 case ABIArgInfo::Ignore:
5439 return llvm::UndefValue::get(ArgPtrTy);
5440 }
5441
5442 // Update VAList.
5443 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5444 Builder.CreateStore(Addr, VAListAddrAsBPP);
5445
5446 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005447}
5448
5449void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5450 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5451 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5452 it != ie; ++it)
5453 it->info = classifyType(it->type, 16 * 8);
5454}
5455
5456namespace {
5457class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5458public:
5459 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5460 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5461};
5462} // end anonymous namespace
5463
5464
Robert Lytton0e076492013-08-13 09:43:10 +00005465//===----------------------------------------------------------------------===//
5466// Xcore ABI Implementation
5467//===----------------------------------------------------------------------===//
5468namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005469class XCoreABIInfo : public DefaultABIInfo {
5470public:
5471 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5472 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5473 CodeGenFunction &CGF) const;
5474};
5475
Robert Lytton0e076492013-08-13 09:43:10 +00005476class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5477public:
5478 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005479 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005480};
Robert Lytton2d196952013-10-11 10:29:34 +00005481} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005482
Robert Lytton7d1db152013-08-19 09:46:39 +00005483llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5484 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005485 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005486
Robert Lytton2d196952013-10-11 10:29:34 +00005487 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005488 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5489 CGF.Int8PtrPtrTy);
5490 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005491
Robert Lytton2d196952013-10-11 10:29:34 +00005492 // Handle the argument.
5493 ABIArgInfo AI = classifyArgumentType(Ty);
5494 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5495 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5496 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005497 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005498 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005499 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005500 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005501 case ABIArgInfo::Expand:
5502 llvm_unreachable("Unsupported ABI kind for va_arg");
5503 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005504 Val = llvm::UndefValue::get(ArgPtrTy);
5505 ArgSize = 0;
5506 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005507 case ABIArgInfo::Extend:
5508 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005509 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5510 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5511 if (ArgSize < 4)
5512 ArgSize = 4;
5513 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005514 case ABIArgInfo::Indirect:
5515 llvm::Value *ArgAddr;
5516 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5517 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005518 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5519 ArgSize = 4;
5520 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005521 }
Robert Lytton2d196952013-10-11 10:29:34 +00005522
5523 // Increment the VAList.
5524 if (ArgSize) {
5525 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5526 Builder.CreateStore(APN, VAListAddrAsBPP);
5527 }
5528 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005529}
Robert Lytton0e076492013-08-13 09:43:10 +00005530
5531//===----------------------------------------------------------------------===//
5532// Driver code
5533//===----------------------------------------------------------------------===//
5534
Chris Lattner2b037972010-07-29 02:01:43 +00005535const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005536 if (TheTargetCodeGenInfo)
5537 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005538
John McCallc8e01702013-04-16 22:48:15 +00005539 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005540 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005541 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005542 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005543
Derek Schuff09338a22012-09-06 17:37:28 +00005544 case llvm::Triple::le32:
5545 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005546 case llvm::Triple::mips:
5547 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005548 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5549
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005550 case llvm::Triple::mips64:
5551 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005552 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5553
Tim Northover9bb857a2013-01-31 12:13:10 +00005554 case llvm::Triple::aarch64:
5555 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5556
Daniel Dunbard59655c2009-09-12 00:59:49 +00005557 case llvm::Triple::arm:
5558 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005559 {
5560 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005561 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005562 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005563 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005564 (CodeGenOpts.FloatABI != "soft" &&
5565 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005566 Kind = ARMABIInfo::AAPCS_VFP;
5567
Derek Schuffa2020962012-10-16 22:30:41 +00005568 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005569 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005570 return *(TheTargetCodeGenInfo =
5571 new NaClARMTargetCodeGenInfo(Types, Kind));
5572 default:
5573 return *(TheTargetCodeGenInfo =
5574 new ARMTargetCodeGenInfo(Types, Kind));
5575 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005576 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005577
John McCallea8d8bb2010-03-11 00:10:12 +00005578 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005579 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005580 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005581 if (Triple.isOSBinFormatELF())
5582 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5583 else
5584 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005585 case llvm::Triple::ppc64le:
5586 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5587 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005588
Peter Collingbournec947aae2012-05-20 23:28:41 +00005589 case llvm::Triple::nvptx:
5590 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005591 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005592
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005593 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005594 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005595
Ulrich Weigand47445072013-05-06 16:26:41 +00005596 case llvm::Triple::systemz:
5597 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5598
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005599 case llvm::Triple::tce:
5600 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5601
Eli Friedman33465822011-07-08 23:31:17 +00005602 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005603 bool IsDarwinVectorABI = Triple.isOSDarwin();
5604 bool IsSmallStructInRegABI =
5605 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5606 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005607
John McCall1fe2a8c2013-06-18 02:46:29 +00005608 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005609 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005610 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005611 IsDarwinVectorABI, IsSmallStructInRegABI,
5612 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005613 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005614 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005615 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005616 new X86_32TargetCodeGenInfo(Types,
5617 IsDarwinVectorABI, IsSmallStructInRegABI,
5618 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005619 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005620 }
Eli Friedman33465822011-07-08 23:31:17 +00005621 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005622
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005623 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005624 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005625
Chris Lattner04dc9572010-08-31 16:44:54 +00005626 switch (Triple.getOS()) {
5627 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005628 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005629 case llvm::Triple::Cygwin:
5630 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005631 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005632 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5633 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005634 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005635 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5636 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005637 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005638 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005639 case llvm::Triple::hexagon:
5640 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005641 case llvm::Triple::sparcv9:
5642 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005643 case llvm::Triple::xcore:
5644 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5645
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005646 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005647}