blob: e1c586a7d287be33d99d6623f11612a795c8bf1d [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;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000117 case InAlloca:
118 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
119 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000120 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000121 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000122 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000123 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127 break;
128 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000129 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000130}
131
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000132TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
133
John McCall3480ef22011-08-30 01:42:09 +0000134// If someone can figure out a general rule for this, that would be great.
135// It's probably just doomed to be platform-dependent, though.
136unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
137 // Verified for:
138 // x86-64 FreeBSD, Linux, Darwin
139 // x86-32 FreeBSD, Linux, Darwin
140 // PowerPC Linux, Darwin
141 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000142 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000143 return 32;
144}
145
John McCalla729c622012-02-17 03:33:10 +0000146bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
147 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000148 // The following conventions are known to require this to be false:
149 // x86_stdcall
150 // MIPS
151 // For everything else, we just prefer false unless we opt out.
152 return false;
153}
154
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000155void
156TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
157 llvm::SmallString<24> &Opt) const {
158 // This assumes the user is passing a library name like "rt" instead of a
159 // filename like "librt.a/so", and that they don't care whether it's static or
160 // dynamic.
161 Opt = "-l";
162 Opt += Lib;
163}
164
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000165static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000166
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000167/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000169static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
170 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000171 if (FD->isUnnamedBitfield())
172 return true;
173
174 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000175
Eli Friedman0b3f2012011-11-18 03:47:20 +0000176 // Constant arrays of empty records count as empty, strip them off.
177 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000178 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000179 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
180 if (AT->getSize() == 0)
181 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000182 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000183 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000185 const RecordType *RT = FT->getAs<RecordType>();
186 if (!RT)
187 return false;
188
189 // C++ record fields are never empty, at least in the Itanium ABI.
190 //
191 // FIXME: We should use a predicate for whether this behavior is true in the
192 // current ABI.
193 if (isa<CXXRecordDecl>(RT->getDecl()))
194 return false;
195
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000196 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197}
198
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000199/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000200/// fields. Note that a structure with a flexible array member is not
201/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000202static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000203 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000204 if (!RT)
205 return 0;
206 const RecordDecl *RD = RT->getDecl();
207 if (RD->hasFlexibleArrayMember())
208 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000209
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000210 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000211 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000212 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
213 e = CXXRD->bases_end(); i != e; ++i)
214 if (!isEmptyRecord(Context, i->getType(), true))
215 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000216
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000217 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
218 i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +0000219 if (!isEmptyField(Context, *i, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000220 return false;
221 return true;
222}
223
224/// isSingleElementStruct - Determine if a structure is a "single
225/// element struct", i.e. it has exactly one non-empty field or
226/// exactly one field which is itself a single element
227/// struct. Structures with flexible array members are never
228/// considered single element structs.
229///
230/// \return The field declaration for the single non-empty field, if
231/// it exists.
232static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
233 const RecordType *RT = T->getAsStructureType();
234 if (!RT)
235 return 0;
236
237 const RecordDecl *RD = RT->getDecl();
238 if (RD->hasFlexibleArrayMember())
239 return 0;
240
241 const Type *Found = 0;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000242
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000243 // If this is a C++ record, check the bases first.
244 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
245 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
246 e = CXXRD->bases_end(); i != e; ++i) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000247 // Ignore empty records.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000248 if (isEmptyRecord(Context, i->getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000249 continue;
250
251 // If we already found an element then this isn't a single-element struct.
252 if (Found)
253 return 0;
254
255 // If this is non-empty and not a single element struct, the composite
256 // cannot be a single element struct.
257 Found = isSingleElementStruct(i->getType(), Context);
258 if (!Found)
259 return 0;
260 }
261 }
262
263 // Check for single element.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000264 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
265 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000266 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000267 QualType FT = FD->getType();
268
269 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000270 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000271 continue;
272
273 // If we already found an element then this isn't a single-element
274 // struct.
275 if (Found)
276 return 0;
277
278 // Treat single element arrays as the element.
279 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
280 if (AT->getSize().getZExtValue() != 1)
281 break;
282 FT = AT->getElementType();
283 }
284
John McCalla1dee5302010-08-22 10:59:02 +0000285 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000286 Found = FT.getTypePtr();
287 } else {
288 Found = isSingleElementStruct(FT, Context);
289 if (!Found)
290 return 0;
291 }
292 }
293
Eli Friedmanee945342011-11-18 01:25:50 +0000294 // We don't consider a struct a single-element struct if it has
295 // padding beyond the element type.
296 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
297 return 0;
298
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000299 return Found;
300}
301
302static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000303 // Treat complex types as the element type.
304 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
305 Ty = CTy->getElementType();
306
307 // Check for a type which we know has a simple scalar argument-passing
308 // convention without any padding. (We're specifically looking for 32
309 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000310 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000311 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000312 return false;
313
314 uint64_t Size = Context.getTypeSize(Ty);
315 return Size == 32 || Size == 64;
316}
317
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000318/// canExpandIndirectArgument - Test whether an argument type which is to be
319/// passed indirectly (on the stack) would have the equivalent layout if it was
320/// expanded into separate arguments. If so, we prefer to do the latter to avoid
321/// inhibiting optimizations.
322///
323// FIXME: This predicate is missing many cases, currently it just follows
324// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
325// should probably make this smarter, or better yet make the LLVM backend
326// capable of handling it.
327static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
328 // We can only expand structure types.
329 const RecordType *RT = Ty->getAs<RecordType>();
330 if (!RT)
331 return false;
332
333 // We can only expand (C) structures.
334 //
335 // FIXME: This needs to be generalized to handle classes as well.
336 const RecordDecl *RD = RT->getDecl();
337 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
338 return false;
339
Eli Friedmane5c85622011-11-18 01:32:26 +0000340 uint64_t Size = 0;
341
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000342 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
343 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000344 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000345
346 if (!is32Or64BitBasicType(FD->getType(), Context))
347 return false;
348
349 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
350 // how to expand them yet, and the predicate for telling if a bitfield still
351 // counts as "basic" is more complicated than what we were doing previously.
352 if (FD->isBitField())
353 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000354
355 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000356 }
357
Eli Friedmane5c85622011-11-18 01:32:26 +0000358 // Make sure there are not any holes in the struct.
359 if (Size != Context.getTypeSize(Ty))
360 return false;
361
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000362 return true;
363}
364
365namespace {
366/// DefaultABIInfo - The default implementation for ABI specific
367/// details. This implementation provides information which results in
368/// self-consistent and sensible LLVM IR generation, but does not
369/// conform to any particular ABI.
370class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000371public:
372 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000373
Chris Lattner458b2aa2010-07-29 02:16:43 +0000374 ABIArgInfo classifyReturnType(QualType RetTy) const;
375 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000376
Chris Lattner22326a12010-07-29 02:31:05 +0000377 virtual void computeInfo(CGFunctionInfo &FI) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000378 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000379 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
380 it != ie; ++it)
Chris Lattner458b2aa2010-07-29 02:16:43 +0000381 it->info = classifyArgumentType(it->type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000382 }
383
384 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
385 CodeGenFunction &CGF) const;
386};
387
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000388class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
389public:
Chris Lattner2b037972010-07-29 02:01:43 +0000390 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
391 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000392};
393
394llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
395 CodeGenFunction &CGF) const {
396 return 0;
397}
398
Chris Lattner458b2aa2010-07-29 02:16:43 +0000399ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung180319f2011-11-03 00:59:44 +0000400 if (isAggregateTypeForABI(Ty)) {
Alp Tokerd4733632013-12-05 04:47:09 +0000401 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung180319f2011-11-03 00:59:44 +0000402 // by value.
Mark Lacey3825e832013-10-06 01:33:34 +0000403 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung180319f2011-11-03 00:59:44 +0000404 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
405
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000406 return ABIArgInfo::getIndirect(0);
Jan Wen Voung180319f2011-11-03 00:59:44 +0000407 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000408
Chris Lattner9723d6c2010-03-11 18:19:55 +0000409 // Treat an enum type as its underlying type.
410 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
411 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000412
Chris Lattner9723d6c2010-03-11 18:19:55 +0000413 return (Ty->isPromotableIntegerType() ?
414 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000415}
416
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000417ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
418 if (RetTy->isVoidType())
419 return ABIArgInfo::getIgnore();
420
421 if (isAggregateTypeForABI(RetTy))
422 return ABIArgInfo::getIndirect(0);
423
424 // Treat an enum type as its underlying type.
425 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
426 RetTy = EnumTy->getDecl()->getIntegerType();
427
428 return (RetTy->isPromotableIntegerType() ?
429 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
430}
431
Derek Schuff09338a22012-09-06 17:37:28 +0000432//===----------------------------------------------------------------------===//
433// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000434//
435// This is a simplified version of the x86_32 ABI. Arguments and return values
436// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000437//===----------------------------------------------------------------------===//
438
439class PNaClABIInfo : public ABIInfo {
440 public:
441 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
442
443 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000444 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000445
446 virtual void computeInfo(CGFunctionInfo &FI) const;
447 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
448 CodeGenFunction &CGF) const;
449};
450
451class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
452 public:
453 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
454 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
455};
456
457void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
458 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
459
Derek Schuff09338a22012-09-06 17:37:28 +0000460 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
461 it != ie; ++it)
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000462 it->info = classifyArgumentType(it->type);
Derek Schuff09338a22012-09-06 17:37:28 +0000463 }
464
465llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
466 CodeGenFunction &CGF) const {
467 return 0;
468}
469
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000470/// \brief Classify argument of given type \p Ty.
471ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000472 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000473 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000474 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000475 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000476 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
477 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000478 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000479 } else if (Ty->isFloatingType()) {
480 // Floating-point types don't go inreg.
481 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000482 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000483
484 return (Ty->isPromotableIntegerType() ?
485 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000486}
487
488ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
489 if (RetTy->isVoidType())
490 return ABIArgInfo::getIgnore();
491
Eli Benderskye20dad62013-04-04 22:49:35 +0000492 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000493 if (isAggregateTypeForABI(RetTy))
494 return ABIArgInfo::getIndirect(0);
495
496 // Treat an enum type as its underlying type.
497 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
498 RetTy = EnumTy->getDecl()->getIntegerType();
499
500 return (RetTy->isPromotableIntegerType() ?
501 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
502}
503
Chad Rosier651c1832013-03-25 21:00:27 +0000504/// IsX86_MMXType - Return true if this is an MMX type.
505bool IsX86_MMXType(llvm::Type *IRType) {
506 // 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 +0000507 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
508 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
509 IRType->getScalarSizeInBits() != 64;
510}
511
Jay Foad7c57be32011-07-11 09:56:20 +0000512static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000514 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000515 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
516 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
517 // Invalid MMX constraint
518 return 0;
519 }
520
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000521 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000522 }
523
524 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000525 return Ty;
526}
527
Chris Lattner0cf24192010-06-28 20:05:43 +0000528//===----------------------------------------------------------------------===//
529// X86-32 ABI Implementation
530//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000531
Reid Kleckner661f35b2014-01-18 01:12:41 +0000532/// \brief Similar to llvm::CCState, but for Clang.
533struct CCState {
534 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
535
536 unsigned CC;
537 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000538 unsigned StackOffset;
539 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000540};
541
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000542/// X86_32ABIInfo - The X86-32 ABI information.
543class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000544 enum Class {
545 Integer,
546 Float
547 };
548
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000549 static const unsigned MinABIStackAlignInBytes = 4;
550
David Chisnallde3a0692009-08-17 23:08:21 +0000551 bool IsDarwinVectorABI;
552 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000553 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000554 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000555
556 static bool isRegisterSize(unsigned Size) {
557 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
558 }
559
Reid Kleckner4982b822014-01-31 22:54:50 +0000560 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
561 bool IsInstanceMethod) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000562
Daniel Dunbar557893d2010-04-21 19:10:51 +0000563 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
564 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000565 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
566
567 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000568
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000569 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000570 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000571
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000572 Class classify(QualType Ty) const;
Reid Kleckner4982b822014-01-31 22:54:50 +0000573 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State,
574 bool IsInstanceMethod) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000575 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
576 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000577
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000578 /// \brief Rewrite the function info so that all memory arguments use
579 /// inalloca.
580 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
581
582 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
583 unsigned &StackOffset, ABIArgInfo &Info,
584 QualType Type) const;
585
Rafael Espindola75419dc2012-07-23 23:30:29 +0000586public:
587
Rafael Espindolaa6472962012-07-24 00:01:07 +0000588 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000589 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
590 CodeGenFunction &CGF) const;
591
Chad Rosier651c1832013-03-25 21:00:27 +0000592 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000593 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000594 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000595 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000596};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000597
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000598class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
599public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000600 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000601 bool d, bool p, bool w, unsigned r)
602 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000603
John McCall1fe2a8c2013-06-18 02:46:29 +0000604 static bool isStructReturnInRegABI(
605 const llvm::Triple &Triple, const CodeGenOptions &Opts);
606
Charles Davis4ea31ab2010-02-13 15:54:06 +0000607 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
608 CodeGen::CodeGenModule &CGM) const;
John McCallbeec5a02010-03-06 00:35:14 +0000609
610 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
611 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000612 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000613 return 4;
614 }
615
616 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
617 llvm::Value *Address) const;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000618
Jay Foad7c57be32011-07-11 09:56:20 +0000619 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000621 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000622 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
623 }
624
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000625 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
626 unsigned Sig = (0xeb << 0) | // jmp rel8
627 (0x06 << 8) | // .+0x08
628 ('F' << 16) |
629 ('T' << 24);
630 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
631 }
632
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000633};
634
635}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000636
637/// shouldReturnTypeInRegister - Determine if the given type should be
638/// passed in a register (for the Darwin ABI).
Reid Kleckner4982b822014-01-31 22:54:50 +0000639bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
640 bool IsInstanceMethod) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000641 uint64_t Size = Context.getTypeSize(Ty);
642
643 // Type must be register sized.
644 if (!isRegisterSize(Size))
645 return false;
646
647 if (Ty->isVectorType()) {
648 // 64- and 128- bit vectors inside structures are not returned in
649 // registers.
650 if (Size == 64 || Size == 128)
651 return false;
652
653 return true;
654 }
655
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000656 // If this is a builtin, pointer, enum, complex type, member pointer, or
657 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000658 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000659 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000660 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000661 return true;
662
663 // Arrays are treated like records.
664 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman3c424412012-02-22 03:04:13 +0000665 return shouldReturnTypeInRegister(AT->getElementType(), Context,
Reid Kleckner4982b822014-01-31 22:54:50 +0000666 IsInstanceMethod);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000667
668 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000669 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000670 if (!RT) return false;
671
Anders Carlsson40446e82010-01-27 03:25:19 +0000672 // FIXME: Traverse bases here too.
673
Aaron Ballman3c424412012-02-22 03:04:13 +0000674 // For thiscall conventions, structures will never be returned in
675 // a register. This is for compatibility with the MSVC ABI
Reid Kleckner4982b822014-01-31 22:54:50 +0000676 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType())
Aaron Ballman3c424412012-02-22 03:04:13 +0000677 return false;
Aaron Ballman3c424412012-02-22 03:04:13 +0000678
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000679 // Structure types are passed in register if all fields would be
680 // passed in a register.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000681 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
682 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000683 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000684
685 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000686 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000687 continue;
688
689 // Check fields recursively.
Reid Kleckner4982b822014-01-31 22:54:50 +0000690 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000691 return false;
692 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000693 return true;
694}
695
Reid Kleckner661f35b2014-01-18 01:12:41 +0000696ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
697 // If the return value is indirect, then the hidden argument is consuming one
698 // integer register.
699 if (State.FreeRegs) {
700 --State.FreeRegs;
701 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
702 }
703 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
704}
705
Reid Kleckner4982b822014-01-31 22:54:50 +0000706ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State,
707 bool IsInstanceMethod) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000708 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000709 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000710
Chris Lattner458b2aa2010-07-29 02:16:43 +0000711 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000712 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000713 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000714 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000715
716 // 128-bit vectors are a special case; they are returned in
717 // registers and we need to make sure to pick a type the LLVM
718 // backend will like.
719 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000720 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000721 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000722
723 // Always return in register if it fits in a general purpose
724 // register, or if it is 64 bits and has a single element.
725 if ((Size == 8 || Size == 16 || Size == 32) ||
726 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000727 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000728 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000729
Reid Kleckner661f35b2014-01-18 01:12:41 +0000730 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000731 }
732
733 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000734 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000735
John McCalla1dee5302010-08-22 10:59:02 +0000736 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000737 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000738 if (isRecordReturnIndirect(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000739 return getIndirectReturnResult(State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000740
Anders Carlsson5789c492009-10-20 22:07:59 +0000741 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000742 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000743 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000744 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000745
David Chisnallde3a0692009-08-17 23:08:21 +0000746 // If specified, structs and unions are always indirect.
747 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000748 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000749
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000750 // Small structures which are register sized are generally returned
751 // in a register.
Reid Kleckner4982b822014-01-31 22:54:50 +0000752 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000753 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000754
755 // As a special-case, if the struct is a "single-element" struct, and
756 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000757 // floating-point register. (MSVC does not apply this special case.)
758 // We apply a similar transformation for pointer types to improve the
759 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000760 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000761 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000762 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000763 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
764
765 // FIXME: We should be able to narrow this integer in cases with dead
766 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000767 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000768 }
769
Reid Kleckner661f35b2014-01-18 01:12:41 +0000770 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000771 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000772
Chris Lattner458b2aa2010-07-29 02:16:43 +0000773 // Treat an enum type as its underlying type.
774 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
775 RetTy = EnumTy->getDecl()->getIntegerType();
776
777 return (RetTy->isPromotableIntegerType() ?
778 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000779}
780
Eli Friedman7919bea2012-06-05 19:40:46 +0000781static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
782 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
783}
784
Daniel Dunbared23de32010-09-16 20:42:00 +0000785static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
786 const RecordType *RT = Ty->getAs<RecordType>();
787 if (!RT)
788 return 0;
789 const RecordDecl *RD = RT->getDecl();
790
791 // If this is a C++ record, check the bases first.
792 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
793 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
794 e = CXXRD->bases_end(); i != e; ++i)
795 if (!isRecordWithSSEVectorType(Context, i->getType()))
796 return false;
797
798 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
799 i != e; ++i) {
800 QualType FT = i->getType();
801
Eli Friedman7919bea2012-06-05 19:40:46 +0000802 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000803 return true;
804
805 if (isRecordWithSSEVectorType(Context, FT))
806 return true;
807 }
808
809 return false;
810}
811
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000812unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
813 unsigned Align) const {
814 // Otherwise, if the alignment is less than or equal to the minimum ABI
815 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000816 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000817 return 0; // Use default alignment.
818
819 // On non-Darwin, the stack type alignment is always 4.
820 if (!IsDarwinVectorABI) {
821 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000822 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000823 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000824
Daniel Dunbared23de32010-09-16 20:42:00 +0000825 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000826 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
827 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000828 return 16;
829
830 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000831}
832
Rafael Espindola703c47f2012-10-19 05:04:37 +0000833ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000834 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000835 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000836 if (State.FreeRegs) {
837 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000838 return ABIArgInfo::getIndirectInReg(0, false);
839 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000840 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000841 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000842
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000843 // Compute the byval alignment.
844 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
845 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
846 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000847 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000848
849 // If the stack alignment is less than the type alignment, realign the
850 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000851 bool Realign = TypeAlign > StackAlign;
852 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000853}
854
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000855X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
856 const Type *T = isSingleElementStruct(Ty, getContext());
857 if (!T)
858 T = Ty.getTypePtr();
859
860 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
861 BuiltinType::Kind K = BT->getKind();
862 if (K == BuiltinType::Float || K == BuiltinType::Double)
863 return Float;
864 }
865 return Integer;
866}
867
Reid Kleckner661f35b2014-01-18 01:12:41 +0000868bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
869 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000870 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000871 Class C = classify(Ty);
872 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000873 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000874
Rafael Espindola077dd592012-10-24 01:58:58 +0000875 unsigned Size = getContext().getTypeSize(Ty);
876 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000877
878 if (SizeInRegs == 0)
879 return false;
880
Reid Kleckner661f35b2014-01-18 01:12:41 +0000881 if (SizeInRegs > State.FreeRegs) {
882 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000883 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000884 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000885
Reid Kleckner661f35b2014-01-18 01:12:41 +0000886 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000887
Reid Kleckner661f35b2014-01-18 01:12:41 +0000888 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000889 if (Size > 32)
890 return false;
891
892 if (Ty->isIntegralOrEnumerationType())
893 return true;
894
895 if (Ty->isPointerType())
896 return true;
897
898 if (Ty->isReferenceType())
899 return true;
900
Reid Kleckner661f35b2014-01-18 01:12:41 +0000901 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000902 NeedsPadding = true;
903
Rafael Espindola077dd592012-10-24 01:58:58 +0000904 return false;
905 }
906
Rafael Espindola703c47f2012-10-19 05:04:37 +0000907 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000908}
909
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000910ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
911 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000912 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000913 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000914 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000915 // Check with the C++ ABI first.
916 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
917 if (RAA == CGCXXABI::RAA_Indirect) {
918 return getIndirectResult(Ty, false, State);
919 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
920 // The field index doesn't matter, we'll fix it up later.
921 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
922 }
923
924 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000925 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000926 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000927
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000928 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000929 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000930 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000931 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000932
Eli Friedman9f061a32011-11-18 00:28:11 +0000933 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000934 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000935 return ABIArgInfo::getIgnore();
936
Rafael Espindolafad28de2012-10-24 01:59:00 +0000937 llvm::LLVMContext &LLVMContext = getVMContext();
938 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
939 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000940 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000941 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000942 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000943 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
944 return ABIArgInfo::getDirectInReg(Result);
945 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000946 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000947
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000948 // Expand small (<= 128-bit) record types when we know that the stack layout
949 // of those arguments will match the struct. This is important because the
950 // LLVM backend isn't smart enough to remove byval, which inhibits many
951 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000952 if (getContext().getTypeSize(Ty) <= 4*32 &&
953 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000954 return ABIArgInfo::getExpandWithPadding(
955 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000956
Reid Kleckner661f35b2014-01-18 01:12:41 +0000957 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000958 }
959
Chris Lattnerd774ae92010-08-26 20:05:13 +0000960 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000961 // On Darwin, some vectors are passed in memory, we handle this by passing
962 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000963 if (IsDarwinVectorABI) {
964 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000965 if ((Size == 8 || Size == 16 || Size == 32) ||
966 (Size == 64 && VT->getNumElements() == 1))
967 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
968 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000969 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000970
Chad Rosier651c1832013-03-25 21:00:27 +0000971 if (IsX86_MMXType(CGT.ConvertType(Ty)))
972 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000973
Chris Lattnerd774ae92010-08-26 20:05:13 +0000974 return ABIArgInfo::getDirect();
975 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000976
977
Chris Lattner458b2aa2010-07-29 02:16:43 +0000978 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
979 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000980
Rafael Espindolafad28de2012-10-24 01:59:00 +0000981 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000982 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000983
984 if (Ty->isPromotableIntegerType()) {
985 if (InReg)
986 return ABIArgInfo::getExtendInReg();
987 return ABIArgInfo::getExtend();
988 }
989 if (InReg)
990 return ABIArgInfo::getDirectInReg();
991 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000992}
993
Rafael Espindolaa6472962012-07-24 00:01:07 +0000994void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000995 CCState State(FI.getCallingConvention());
996 if (State.CC == llvm::CallingConv::X86_FastCall)
997 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000998 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000999 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001000 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001001 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001002
Reid Kleckner4982b822014-01-31 22:54:50 +00001003 FI.getReturnInfo() =
1004 classifyReturnType(FI.getReturnType(), State, FI.isInstanceMethod());
1005
1006 // On win32, use the x86_cdeclmethodcc convention for cdecl methods that use
1007 // sret. This convention swaps the order of the first two parameters behind
1008 // the scenes to match MSVC.
1009 if (IsWin32StructABI && FI.isInstanceMethod() &&
1010 FI.getCallingConvention() == llvm::CallingConv::C &&
1011 FI.getReturnInfo().isIndirect())
1012 FI.setEffectiveCallingConvention(llvm::CallingConv::X86_CDeclMethod);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001013
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001014 bool UsedInAlloca = false;
Rafael Espindolaa6472962012-07-24 00:01:07 +00001015 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001016 it != ie; ++it) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001017 it->info = classifyArgumentType(it->type, State);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001018 UsedInAlloca |= (it->info.getKind() == ABIArgInfo::InAlloca);
1019 }
1020
1021 // If we needed to use inalloca for any argument, do a second pass and rewrite
1022 // all the memory arguments to use inalloca.
1023 if (UsedInAlloca)
1024 rewriteWithInAlloca(FI);
1025}
1026
1027void
1028X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1029 unsigned &StackOffset,
1030 ABIArgInfo &Info, QualType Type) const {
1031 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1032 // byte aligned.
1033 unsigned Align = 4U;
1034 if (Info.getKind() == ABIArgInfo::Indirect && Info.getIndirectByVal())
1035 Align = std::max(Align, Info.getIndirectAlign());
1036 if (StackOffset & (Align - 1)) {
1037 unsigned OldOffset = StackOffset;
1038 StackOffset = llvm::RoundUpToAlignment(StackOffset, Align);
1039 unsigned NumBytes = StackOffset - OldOffset;
1040 assert(NumBytes);
1041 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1042 Ty = llvm::ArrayType::get(Ty, NumBytes);
1043 FrameFields.push_back(Ty);
1044 }
1045
1046 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1047 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1048 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1049}
1050
1051void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1052 assert(IsWin32StructABI && "inalloca only supported on win32");
1053
1054 // Build a packed struct type for all of the arguments in memory.
1055 SmallVector<llvm::Type *, 6> FrameFields;
1056
1057 unsigned StackOffset = 0;
1058
1059 // Put the sret parameter into the inalloca struct if it's in memory.
1060 ABIArgInfo &Ret = FI.getReturnInfo();
1061 if (Ret.isIndirect() && !Ret.getInReg()) {
1062 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1063 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001064 // On Windows, the hidden sret parameter is always returned in eax.
1065 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001066 }
1067
1068 // Skip the 'this' parameter in ecx.
1069 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1070 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall)
1071 ++I;
1072
1073 // Put arguments passed in memory into the struct.
1074 for (; I != E; ++I) {
1075
1076 // Leave ignored and inreg arguments alone.
1077 switch (I->info.getKind()) {
1078 case ABIArgInfo::Indirect:
1079 assert(I->info.getIndirectByVal());
1080 break;
1081 case ABIArgInfo::Ignore:
1082 continue;
1083 case ABIArgInfo::Direct:
1084 case ABIArgInfo::Extend:
1085 if (I->info.getInReg())
1086 continue;
1087 break;
1088 default:
1089 break;
1090 }
1091
1092 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1093 }
1094
1095 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1096 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001097}
1098
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001099llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1100 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001101 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001102
1103 CGBuilderTy &Builder = CGF.Builder;
1104 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1105 "ap");
1106 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001107
1108 // Compute if the address needs to be aligned
1109 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1110 Align = getTypeStackAlignInBytes(Ty, Align);
1111 Align = std::max(Align, 4U);
1112 if (Align > 4) {
1113 // addr = (addr + align - 1) & -align;
1114 llvm::Value *Offset =
1115 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1116 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1117 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1118 CGF.Int32Ty);
1119 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1120 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1121 Addr->getType(),
1122 "ap.cur.aligned");
1123 }
1124
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001125 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001126 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001127 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1128
1129 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001130 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001131 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001132 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001133 "ap.next");
1134 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1135
1136 return AddrTyped;
1137}
1138
Charles Davis4ea31ab2010-02-13 15:54:06 +00001139void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1140 llvm::GlobalValue *GV,
1141 CodeGen::CodeGenModule &CGM) const {
1142 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1143 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1144 // Get the LLVM function.
1145 llvm::Function *Fn = cast<llvm::Function>(GV);
1146
1147 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001148 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001149 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001150 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1151 llvm::AttributeSet::get(CGM.getLLVMContext(),
1152 llvm::AttributeSet::FunctionIndex,
1153 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001154 }
1155 }
1156}
1157
John McCallbeec5a02010-03-06 00:35:14 +00001158bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1159 CodeGen::CodeGenFunction &CGF,
1160 llvm::Value *Address) const {
1161 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001162
Chris Lattnerece04092012-02-07 00:39:47 +00001163 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001164
John McCallbeec5a02010-03-06 00:35:14 +00001165 // 0-7 are the eight integer registers; the order is different
1166 // on Darwin (for EH), but the range is the same.
1167 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001168 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001169
John McCallc8e01702013-04-16 22:48:15 +00001170 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001171 // 12-16 are st(0..4). Not sure why we stop at 4.
1172 // These have size 16, which is sizeof(long double) on
1173 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001174 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001175 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001176
John McCallbeec5a02010-03-06 00:35:14 +00001177 } else {
1178 // 9 is %eflags, which doesn't get a size on Darwin for some
1179 // reason.
1180 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1181
1182 // 11-16 are st(0..5). Not sure why we stop at 5.
1183 // These have size 12, which is sizeof(long double) on
1184 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001185 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001186 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1187 }
John McCallbeec5a02010-03-06 00:35:14 +00001188
1189 return false;
1190}
1191
Chris Lattner0cf24192010-06-28 20:05:43 +00001192//===----------------------------------------------------------------------===//
1193// X86-64 ABI Implementation
1194//===----------------------------------------------------------------------===//
1195
1196
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001197namespace {
1198/// X86_64ABIInfo - The X86_64 ABI information.
1199class X86_64ABIInfo : public ABIInfo {
1200 enum Class {
1201 Integer = 0,
1202 SSE,
1203 SSEUp,
1204 X87,
1205 X87Up,
1206 ComplexX87,
1207 NoClass,
1208 Memory
1209 };
1210
1211 /// merge - Implement the X86_64 ABI merging algorithm.
1212 ///
1213 /// Merge an accumulating classification \arg Accum with a field
1214 /// classification \arg Field.
1215 ///
1216 /// \param Accum - The accumulating classification. This should
1217 /// always be either NoClass or the result of a previous merge
1218 /// call. In addition, this should never be Memory (the caller
1219 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001220 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001222 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1223 ///
1224 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1225 /// final MEMORY or SSE classes when necessary.
1226 ///
1227 /// \param AggregateSize - The size of the current aggregate in
1228 /// the classification process.
1229 ///
1230 /// \param Lo - The classification for the parts of the type
1231 /// residing in the low word of the containing object.
1232 ///
1233 /// \param Hi - The classification for the parts of the type
1234 /// residing in the higher words of the containing object.
1235 ///
1236 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1237
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001238 /// classify - Determine the x86_64 register classes in which the
1239 /// given type T should be passed.
1240 ///
1241 /// \param Lo - The classification for the parts of the type
1242 /// residing in the low word of the containing object.
1243 ///
1244 /// \param Hi - The classification for the parts of the type
1245 /// residing in the high word of the containing object.
1246 ///
1247 /// \param OffsetBase - The bit offset of this type in the
1248 /// containing object. Some parameters are classified different
1249 /// depending on whether they straddle an eightbyte boundary.
1250 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001251 /// \param isNamedArg - Whether the argument in question is a "named"
1252 /// argument, as used in AMD64-ABI 3.5.7.
1253 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001254 /// If a word is unused its result will be NoClass; if a type should
1255 /// be passed in Memory then at least the classification of \arg Lo
1256 /// will be Memory.
1257 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001258 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001259 ///
1260 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1261 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001262 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1263 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001264
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001265 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001266 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1267 unsigned IROffset, QualType SourceTy,
1268 unsigned SourceOffset) const;
1269 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1270 unsigned IROffset, QualType SourceTy,
1271 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001272
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001273 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001274 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001275 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001276
1277 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001279 ///
1280 /// \param freeIntRegs - The number of free integer registers remaining
1281 /// available.
1282 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001283
Chris Lattner458b2aa2010-07-29 02:16:43 +00001284 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001285
Bill Wendling5cd41c42010-10-18 03:41:31 +00001286 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001287 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001288 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001289 unsigned &neededSSE,
1290 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001291
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001292 bool IsIllegalVectorType(QualType Ty) const;
1293
John McCalle0fda732011-04-21 01:20:55 +00001294 /// The 0.98 ABI revision clarified a lot of ambiguities,
1295 /// unfortunately in ways that were not always consistent with
1296 /// certain previous compilers. In particular, platforms which
1297 /// required strict binary compatibility with older versions of GCC
1298 /// may need to exempt themselves.
1299 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001300 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001301 }
1302
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001303 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001304 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1305 // 64-bit hardware.
1306 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001307
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001308public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001309 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001310 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001311 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001312 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001313
John McCalla729c622012-02-17 03:33:10 +00001314 bool isPassedUsingAVXType(QualType type) const {
1315 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001316 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001317 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1318 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001319 if (info.isDirect()) {
1320 llvm::Type *ty = info.getCoerceToType();
1321 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1322 return (vectorTy->getBitWidth() > 128);
1323 }
1324 return false;
1325 }
1326
Chris Lattner22326a12010-07-29 02:31:05 +00001327 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001328
1329 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1330 CodeGenFunction &CGF) const;
1331};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001332
Chris Lattner04dc9572010-08-31 16:44:54 +00001333/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001334class WinX86_64ABIInfo : public ABIInfo {
1335
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001336 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001337
Chris Lattner04dc9572010-08-31 16:44:54 +00001338public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001339 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1340
1341 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattner04dc9572010-08-31 16:44:54 +00001342
1343 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1344 CodeGenFunction &CGF) const;
1345};
1346
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001347class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1348public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001349 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001350 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001351
John McCalla729c622012-02-17 03:33:10 +00001352 const X86_64ABIInfo &getABIInfo() const {
1353 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1354 }
1355
John McCallbeec5a02010-03-06 00:35:14 +00001356 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1357 return 7;
1358 }
1359
1360 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1361 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001362 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001363
John McCall943fae92010-05-27 06:19:26 +00001364 // 0-15 are the 16 integer registers.
1365 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001366 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001367 return false;
1368 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001369
Jay Foad7c57be32011-07-11 09:56:20 +00001370 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001371 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +00001372 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001373 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1374 }
1375
John McCalla729c622012-02-17 03:33:10 +00001376 bool isNoProtoCallVariadic(const CallArgList &args,
1377 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +00001378 // The default CC on x86-64 sets %al to the number of SSA
1379 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001380 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001381 // that when AVX types are involved: the ABI explicitly states it is
1382 // undefined, and it doesn't work in practice because of how the ABI
1383 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001384 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001385 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001386 for (CallArgList::const_iterator
1387 it = args.begin(), ie = args.end(); it != ie; ++it) {
1388 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1389 HasAVXType = true;
1390 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001391 }
1392 }
John McCalla729c622012-02-17 03:33:10 +00001393
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001394 if (!HasAVXType)
1395 return true;
1396 }
John McCallcbc038a2011-09-21 08:08:30 +00001397
John McCalla729c622012-02-17 03:33:10 +00001398 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001399 }
1400
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001401 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
1402 unsigned Sig = (0xeb << 0) | // jmp rel8
1403 (0x0a << 8) | // .+0x0c
1404 ('F' << 16) |
1405 ('T' << 24);
1406 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1407 }
1408
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001409};
1410
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001411static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1412 // If the argument does not end in .lib, automatically add the suffix. This
1413 // matches the behavior of MSVC.
1414 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001415 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001416 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001417 return ArgStr;
1418}
1419
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001420class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1421public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001422 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1423 bool d, bool p, bool w, unsigned RegParms)
1424 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001425
1426 void getDependentLibraryOption(llvm::StringRef Lib,
1427 llvm::SmallString<24> &Opt) const {
1428 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001429 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001430 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001431
1432 void getDetectMismatchOption(llvm::StringRef Name,
1433 llvm::StringRef Value,
1434 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001435 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001436 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001437};
1438
Chris Lattner04dc9572010-08-31 16:44:54 +00001439class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1440public:
1441 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1442 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1443
1444 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1445 return 7;
1446 }
1447
1448 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1449 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001450 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001451
Chris Lattner04dc9572010-08-31 16:44:54 +00001452 // 0-15 are the 16 integer registers.
1453 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001454 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001455 return false;
1456 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001457
1458 void getDependentLibraryOption(llvm::StringRef Lib,
1459 llvm::SmallString<24> &Opt) const {
1460 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001461 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001462 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001463
1464 void getDetectMismatchOption(llvm::StringRef Name,
1465 llvm::StringRef Value,
1466 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001467 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001468 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001469};
1470
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001471}
1472
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001473void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1474 Class &Hi) const {
1475 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1476 //
1477 // (a) If one of the classes is Memory, the whole argument is passed in
1478 // memory.
1479 //
1480 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1481 // memory.
1482 //
1483 // (c) If the size of the aggregate exceeds two eightbytes and the first
1484 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1485 // argument is passed in memory. NOTE: This is necessary to keep the
1486 // ABI working for processors that don't support the __m256 type.
1487 //
1488 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1489 //
1490 // Some of these are enforced by the merging logic. Others can arise
1491 // only with unions; for example:
1492 // union { _Complex double; unsigned; }
1493 //
1494 // Note that clauses (b) and (c) were added in 0.98.
1495 //
1496 if (Hi == Memory)
1497 Lo = Memory;
1498 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1499 Lo = Memory;
1500 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1501 Lo = Memory;
1502 if (Hi == SSEUp && Lo != SSE)
1503 Hi = SSE;
1504}
1505
Chris Lattnerd776fb12010-06-28 21:43:59 +00001506X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001507 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1508 // classified recursively so that always two fields are
1509 // considered. The resulting class is calculated according to
1510 // the classes of the fields in the eightbyte:
1511 //
1512 // (a) If both classes are equal, this is the resulting class.
1513 //
1514 // (b) If one of the classes is NO_CLASS, the resulting class is
1515 // the other class.
1516 //
1517 // (c) If one of the classes is MEMORY, the result is the MEMORY
1518 // class.
1519 //
1520 // (d) If one of the classes is INTEGER, the result is the
1521 // INTEGER.
1522 //
1523 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1524 // MEMORY is used as class.
1525 //
1526 // (f) Otherwise class SSE is used.
1527
1528 // Accum should never be memory (we should have returned) or
1529 // ComplexX87 (because this cannot be passed in a structure).
1530 assert((Accum != Memory && Accum != ComplexX87) &&
1531 "Invalid accumulated classification during merge.");
1532 if (Accum == Field || Field == NoClass)
1533 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001534 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001535 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001536 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001537 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001538 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001539 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001540 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1541 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001542 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001543 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001544}
1545
Chris Lattner5c740f12010-06-30 19:14:05 +00001546void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001547 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001548 // FIXME: This code can be simplified by introducing a simple value class for
1549 // Class pairs with appropriate constructor methods for the various
1550 // situations.
1551
1552 // FIXME: Some of the split computations are wrong; unaligned vectors
1553 // shouldn't be passed in registers for example, so there is no chance they
1554 // can straddle an eightbyte. Verify & simplify.
1555
1556 Lo = Hi = NoClass;
1557
1558 Class &Current = OffsetBase < 64 ? Lo : Hi;
1559 Current = Memory;
1560
John McCall9dd450b2009-09-21 23:43:11 +00001561 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001562 BuiltinType::Kind k = BT->getKind();
1563
1564 if (k == BuiltinType::Void) {
1565 Current = NoClass;
1566 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1567 Lo = Integer;
1568 Hi = Integer;
1569 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1570 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001571 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1572 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001573 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001574 Current = SSE;
1575 } else if (k == BuiltinType::LongDouble) {
1576 Lo = X87;
1577 Hi = X87Up;
1578 }
1579 // FIXME: _Decimal32 and _Decimal64 are SSE.
1580 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001581 return;
1582 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001583
Chris Lattnerd776fb12010-06-28 21:43:59 +00001584 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001585 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001586 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001587 return;
1588 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001589
Chris Lattnerd776fb12010-06-28 21:43:59 +00001590 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001591 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001592 return;
1593 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001594
Chris Lattnerd776fb12010-06-28 21:43:59 +00001595 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001596 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001597 Lo = Hi = Integer;
1598 else
1599 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001600 return;
1601 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001602
Chris Lattnerd776fb12010-06-28 21:43:59 +00001603 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001604 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001605 if (Size == 32) {
1606 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1607 // float> as integer.
1608 Current = Integer;
1609
1610 // If this type crosses an eightbyte boundary, it should be
1611 // split.
1612 uint64_t EB_Real = (OffsetBase) / 64;
1613 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1614 if (EB_Real != EB_Imag)
1615 Hi = Lo;
1616 } else if (Size == 64) {
1617 // gcc passes <1 x double> in memory. :(
1618 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1619 return;
1620
1621 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001622 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001623 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1624 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1625 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001626 Current = Integer;
1627 else
1628 Current = SSE;
1629
1630 // If this type crosses an eightbyte boundary, it should be
1631 // split.
1632 if (OffsetBase && OffsetBase != 64)
1633 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001634 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001635 // Arguments of 256-bits are split into four eightbyte chunks. The
1636 // least significant one belongs to class SSE and all the others to class
1637 // SSEUP. The original Lo and Hi design considers that types can't be
1638 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1639 // This design isn't correct for 256-bits, but since there're no cases
1640 // where the upper parts would need to be inspected, avoid adding
1641 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001642 //
1643 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1644 // registers if they are "named", i.e. not part of the "..." of a
1645 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001646 Lo = SSE;
1647 Hi = SSEUp;
1648 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001649 return;
1650 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001651
Chris Lattnerd776fb12010-06-28 21:43:59 +00001652 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001653 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001654
Chris Lattner2b037972010-07-29 02:01:43 +00001655 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001656 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001657 if (Size <= 64)
1658 Current = Integer;
1659 else if (Size <= 128)
1660 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001661 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001662 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001663 else if (ET == getContext().DoubleTy ||
1664 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001665 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001666 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001667 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001668 Current = ComplexX87;
1669
1670 // If this complex type crosses an eightbyte boundary then it
1671 // should be split.
1672 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001673 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001674 if (Hi == NoClass && EB_Real != EB_Imag)
1675 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001676
Chris Lattnerd776fb12010-06-28 21:43:59 +00001677 return;
1678 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001679
Chris Lattner2b037972010-07-29 02:01:43 +00001680 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001681 // Arrays are treated like structures.
1682
Chris Lattner2b037972010-07-29 02:01:43 +00001683 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001684
1685 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001686 // than four eightbytes, ..., it has class MEMORY.
1687 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001688 return;
1689
1690 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1691 // fields, it has class MEMORY.
1692 //
1693 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001694 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001695 return;
1696
1697 // Otherwise implement simplified merge. We could be smarter about
1698 // this, but it isn't worth it and would be harder to verify.
1699 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001700 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001701 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001702
1703 // The only case a 256-bit wide vector could be used is when the array
1704 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1705 // to work for sizes wider than 128, early check and fallback to memory.
1706 if (Size > 128 && EltSize != 256)
1707 return;
1708
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001709 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1710 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001711 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001712 Lo = merge(Lo, FieldLo);
1713 Hi = merge(Hi, FieldHi);
1714 if (Lo == Memory || Hi == Memory)
1715 break;
1716 }
1717
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001718 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001719 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001720 return;
1721 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001722
Chris Lattnerd776fb12010-06-28 21:43:59 +00001723 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001724 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001725
1726 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001727 // than four eightbytes, ..., it has class MEMORY.
1728 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001729 return;
1730
Anders Carlsson20759ad2009-09-16 15:53:40 +00001731 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1732 // copy constructor or a non-trivial destructor, it is passed by invisible
1733 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001734 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001735 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001736
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001737 const RecordDecl *RD = RT->getDecl();
1738
1739 // Assume variable sized types are passed in memory.
1740 if (RD->hasFlexibleArrayMember())
1741 return;
1742
Chris Lattner2b037972010-07-29 02:01:43 +00001743 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001744
1745 // Reset Lo class, this will be recomputed.
1746 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001747
1748 // If this is a C++ record, classify the bases first.
1749 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1750 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1751 e = CXXRD->bases_end(); i != e; ++i) {
1752 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1753 "Unexpected base class!");
1754 const CXXRecordDecl *Base =
1755 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1756
1757 // Classify this field.
1758 //
1759 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1760 // single eightbyte, each is classified separately. Each eightbyte gets
1761 // initialized to class NO_CLASS.
1762 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001763 uint64_t Offset =
1764 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman96fd2642013-06-12 00:13:45 +00001765 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001766 Lo = merge(Lo, FieldLo);
1767 Hi = merge(Hi, FieldHi);
1768 if (Lo == Memory || Hi == Memory)
1769 break;
1770 }
1771 }
1772
1773 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001774 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001775 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001776 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001777 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1778 bool BitField = i->isBitField();
1779
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001780 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1781 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001782 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001783 // The only case a 256-bit wide vector could be used is when the struct
1784 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1785 // to work for sizes wider than 128, early check and fallback to memory.
1786 //
1787 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1788 Lo = Memory;
1789 return;
1790 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001791 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001792 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001793 Lo = Memory;
1794 return;
1795 }
1796
1797 // Classify this field.
1798 //
1799 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1800 // exceeds a single eightbyte, each is classified
1801 // separately. Each eightbyte gets initialized to class
1802 // NO_CLASS.
1803 Class FieldLo, FieldHi;
1804
1805 // Bit-fields require special handling, they do not force the
1806 // structure to be passed in memory even if unaligned, and
1807 // therefore they can straddle an eightbyte.
1808 if (BitField) {
1809 // Ignore padding bit-fields.
1810 if (i->isUnnamedBitfield())
1811 continue;
1812
1813 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001814 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001815
1816 uint64_t EB_Lo = Offset / 64;
1817 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001818
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001819 if (EB_Lo) {
1820 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1821 FieldLo = NoClass;
1822 FieldHi = Integer;
1823 } else {
1824 FieldLo = Integer;
1825 FieldHi = EB_Hi ? Integer : NoClass;
1826 }
1827 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001828 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001829 Lo = merge(Lo, FieldLo);
1830 Hi = merge(Hi, FieldHi);
1831 if (Lo == Memory || Hi == Memory)
1832 break;
1833 }
1834
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001835 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001836 }
1837}
1838
Chris Lattner22a931e2010-06-29 06:01:59 +00001839ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001840 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1841 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001842 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001843 // Treat an enum type as its underlying type.
1844 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1845 Ty = EnumTy->getDecl()->getIntegerType();
1846
1847 return (Ty->isPromotableIntegerType() ?
1848 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1849 }
1850
1851 return ABIArgInfo::getIndirect(0);
1852}
1853
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001854bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1855 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1856 uint64_t Size = getContext().getTypeSize(VecTy);
1857 unsigned LargestVector = HasAVX ? 256 : 128;
1858 if (Size <= 64 || Size > LargestVector)
1859 return true;
1860 }
1861
1862 return false;
1863}
1864
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001865ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1866 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001867 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1868 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001869 //
1870 // This assumption is optimistic, as there could be free registers available
1871 // when we need to pass this argument in memory, and LLVM could try to pass
1872 // the argument in the free register. This does not seem to happen currently,
1873 // but this code would be much safer if we could mark the argument with
1874 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001875 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001876 // Treat an enum type as its underlying type.
1877 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1878 Ty = EnumTy->getDecl()->getIntegerType();
1879
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001880 return (Ty->isPromotableIntegerType() ?
1881 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001882 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001883
Mark Lacey3825e832013-10-06 01:33:34 +00001884 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001885 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001886
Chris Lattner44c2b902011-05-22 23:21:23 +00001887 // Compute the byval alignment. We specify the alignment of the byval in all
1888 // cases so that the mid-level optimizer knows the alignment of the byval.
1889 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001890
1891 // Attempt to avoid passing indirect results using byval when possible. This
1892 // is important for good codegen.
1893 //
1894 // We do this by coercing the value into a scalar type which the backend can
1895 // handle naturally (i.e., without using byval).
1896 //
1897 // For simplicity, we currently only do this when we have exhausted all of the
1898 // free integer registers. Doing this when there are free integer registers
1899 // would require more care, as we would have to ensure that the coerced value
1900 // did not claim the unused register. That would require either reording the
1901 // arguments to the function (so that any subsequent inreg values came first),
1902 // or only doing this optimization when there were no following arguments that
1903 // might be inreg.
1904 //
1905 // We currently expect it to be rare (particularly in well written code) for
1906 // arguments to be passed on the stack when there are still free integer
1907 // registers available (this would typically imply large structs being passed
1908 // by value), so this seems like a fair tradeoff for now.
1909 //
1910 // We can revisit this if the backend grows support for 'onstack' parameter
1911 // attributes. See PR12193.
1912 if (freeIntRegs == 0) {
1913 uint64_t Size = getContext().getTypeSize(Ty);
1914
1915 // If this type fits in an eightbyte, coerce it into the matching integral
1916 // type, which will end up on the stack (with alignment 8).
1917 if (Align == 8 && Size <= 64)
1918 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1919 Size));
1920 }
1921
Chris Lattner44c2b902011-05-22 23:21:23 +00001922 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001923}
1924
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001925/// GetByteVectorType - The ABI specifies that a value should be passed in an
1926/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001927/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001928llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001929 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001930
Chris Lattner9fa15c32010-07-29 05:02:29 +00001931 // Wrapper structs that just contain vectors are passed just like vectors,
1932 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001933 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001934 while (STy && STy->getNumElements() == 1) {
1935 IRType = STy->getElementType(0);
1936 STy = dyn_cast<llvm::StructType>(IRType);
1937 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001938
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001939 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001940 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1941 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001942 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001943 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001944 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1945 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1946 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1947 EltTy->isIntegerTy(128)))
1948 return VT;
1949 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001950
Chris Lattner4200fe42010-07-29 04:56:46 +00001951 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1952}
1953
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001954/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1955/// is known to either be off the end of the specified type or being in
1956/// alignment padding. The user type specified is known to be at most 128 bits
1957/// in size, and have passed through X86_64ABIInfo::classify with a successful
1958/// classification that put one of the two halves in the INTEGER class.
1959///
1960/// It is conservatively correct to return false.
1961static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1962 unsigned EndBit, ASTContext &Context) {
1963 // If the bytes being queried are off the end of the type, there is no user
1964 // data hiding here. This handles analysis of builtins, vectors and other
1965 // types that don't contain interesting padding.
1966 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1967 if (TySize <= StartBit)
1968 return true;
1969
Chris Lattner98076a22010-07-29 07:43:55 +00001970 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1971 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1972 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1973
1974 // Check each element to see if the element overlaps with the queried range.
1975 for (unsigned i = 0; i != NumElts; ++i) {
1976 // If the element is after the span we care about, then we're done..
1977 unsigned EltOffset = i*EltSize;
1978 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001979
Chris Lattner98076a22010-07-29 07:43:55 +00001980 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1981 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1982 EndBit-EltOffset, Context))
1983 return false;
1984 }
1985 // If it overlaps no elements, then it is safe to process as padding.
1986 return true;
1987 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001988
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001989 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1990 const RecordDecl *RD = RT->getDecl();
1991 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001992
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001993 // If this is a C++ record, check the bases first.
1994 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1995 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1996 e = CXXRD->bases_end(); i != e; ++i) {
1997 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1998 "Unexpected base class!");
1999 const CXXRecordDecl *Base =
2000 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002001
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002002 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002003 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002004 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002005
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002006 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2007 if (!BitsContainNoUserData(i->getType(), BaseStart,
2008 EndBit-BaseOffset, Context))
2009 return false;
2010 }
2011 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002012
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002013 // Verify that no field has data that overlaps the region of interest. Yes
2014 // this could be sped up a lot by being smarter about queried fields,
2015 // however we're only looking at structs up to 16 bytes, so we don't care
2016 // much.
2017 unsigned idx = 0;
2018 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2019 i != e; ++i, ++idx) {
2020 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002021
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002022 // If we found a field after the region we care about, then we're done.
2023 if (FieldOffset >= EndBit) break;
2024
2025 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2026 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2027 Context))
2028 return false;
2029 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002030
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002031 // If nothing in this record overlapped the area of interest, then we're
2032 // clean.
2033 return true;
2034 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002035
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002036 return false;
2037}
2038
Chris Lattnere556a712010-07-29 18:39:32 +00002039/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2040/// float member at the specified offset. For example, {int,{float}} has a
2041/// float at offset 4. It is conservatively correct for this routine to return
2042/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002043static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002044 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002045 // Base case if we find a float.
2046 if (IROffset == 0 && IRType->isFloatTy())
2047 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002048
Chris Lattnere556a712010-07-29 18:39:32 +00002049 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002050 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002051 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2052 unsigned Elt = SL->getElementContainingOffset(IROffset);
2053 IROffset -= SL->getElementOffset(Elt);
2054 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2055 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002056
Chris Lattnere556a712010-07-29 18:39:32 +00002057 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002058 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2059 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002060 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2061 IROffset -= IROffset/EltSize*EltSize;
2062 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2063 }
2064
2065 return false;
2066}
2067
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002068
2069/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2070/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002071llvm::Type *X86_64ABIInfo::
2072GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002073 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002074 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002075 // pass as float if the last 4 bytes is just padding. This happens for
2076 // structs that contain 3 floats.
2077 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2078 SourceOffset*8+64, getContext()))
2079 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002080
Chris Lattnere556a712010-07-29 18:39:32 +00002081 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2082 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2083 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002084 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2085 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002086 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002087
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002088 return llvm::Type::getDoubleTy(getVMContext());
2089}
2090
2091
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002092/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2093/// an 8-byte GPR. This means that we either have a scalar or we are talking
2094/// about the high or low part of an up-to-16-byte struct. This routine picks
2095/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002096/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2097/// etc).
2098///
2099/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2100/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2101/// the 8-byte value references. PrefType may be null.
2102///
2103/// SourceTy is the source level type for the entire argument. SourceOffset is
2104/// an offset into this that we're processing (which is always either 0 or 8).
2105///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002106llvm::Type *X86_64ABIInfo::
2107GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002108 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002109 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2110 // returning an 8-byte unit starting with it. See if we can safely use it.
2111 if (IROffset == 0) {
2112 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002113 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2114 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002115 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002116
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002117 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2118 // goodness in the source type is just tail padding. This is allowed to
2119 // kick in for struct {double,int} on the int, but not on
2120 // struct{double,int,int} because we wouldn't return the second int. We
2121 // have to do this analysis on the source type because we can't depend on
2122 // unions being lowered a specific way etc.
2123 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002124 IRType->isIntegerTy(32) ||
2125 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2126 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2127 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002128
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002129 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2130 SourceOffset*8+64, getContext()))
2131 return IRType;
2132 }
2133 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002134
Chris Lattner2192fe52011-07-18 04:24:23 +00002135 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002136 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002137 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002138 if (IROffset < SL->getSizeInBytes()) {
2139 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2140 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002141
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002142 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2143 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002144 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002145 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002146
Chris Lattner2192fe52011-07-18 04:24:23 +00002147 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002148 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002149 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002150 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002151 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2152 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002153 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002154
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002155 // Okay, we don't have any better idea of what to pass, so we pass this in an
2156 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002157 unsigned TySizeInBytes =
2158 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002159
Chris Lattner3f763422010-07-29 17:34:39 +00002160 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002161
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002162 // It is always safe to classify this as an integer type up to i64 that
2163 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002164 return llvm::IntegerType::get(getVMContext(),
2165 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002166}
2167
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002168
2169/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2170/// be used as elements of a two register pair to pass or return, return a
2171/// first class aggregate to represent them. For example, if the low part of
2172/// a by-value argument should be passed as i32* and the high part as float,
2173/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002174static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002175GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002176 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002177 // In order to correctly satisfy the ABI, we need to the high part to start
2178 // at offset 8. If the high and low parts we inferred are both 4-byte types
2179 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2180 // the second element at offset 8. Check for this:
2181 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2182 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002183 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002184 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002185
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002186 // To handle this, we have to increase the size of the low part so that the
2187 // second element will start at an 8 byte offset. We can't increase the size
2188 // of the second element because it might make us access off the end of the
2189 // struct.
2190 if (HiStart != 8) {
2191 // There are only two sorts of types the ABI generation code can produce for
2192 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2193 // Promote these to a larger type.
2194 if (Lo->isFloatTy())
2195 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2196 else {
2197 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2198 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2199 }
2200 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002201
Chris Lattnera5f58b02011-07-09 17:41:47 +00002202 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002203
2204
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002205 // Verify that the second element is at an 8-byte offset.
2206 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2207 "Invalid x86-64 argument pair!");
2208 return Result;
2209}
2210
Chris Lattner31faff52010-07-28 23:06:14 +00002211ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002212classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002213 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2214 // classification algorithm.
2215 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002216 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002217
2218 // Check some invariants.
2219 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002220 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2221
Chris Lattnera5f58b02011-07-09 17:41:47 +00002222 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002223 switch (Lo) {
2224 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002225 if (Hi == NoClass)
2226 return ABIArgInfo::getIgnore();
2227 // If the low part is just padding, it takes no register, leave ResType
2228 // null.
2229 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2230 "Unknown missing lo part");
2231 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002232
2233 case SSEUp:
2234 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002235 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002236
2237 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2238 // hidden argument.
2239 case Memory:
2240 return getIndirectReturnResult(RetTy);
2241
2242 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2243 // available register of the sequence %rax, %rdx is used.
2244 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002245 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002246
Chris Lattner1f3a0632010-07-29 21:42:50 +00002247 // If we have a sign or zero extended integer, make sure to return Extend
2248 // so that the parameter gets the right LLVM IR attributes.
2249 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2250 // Treat an enum type as its underlying type.
2251 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2252 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002253
Chris Lattner1f3a0632010-07-29 21:42:50 +00002254 if (RetTy->isIntegralOrEnumerationType() &&
2255 RetTy->isPromotableIntegerType())
2256 return ABIArgInfo::getExtend();
2257 }
Chris Lattner31faff52010-07-28 23:06:14 +00002258 break;
2259
2260 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2261 // available SSE register of the sequence %xmm0, %xmm1 is used.
2262 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002263 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002264 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002265
2266 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2267 // returned on the X87 stack in %st0 as 80-bit x87 number.
2268 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002269 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002270 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002271
2272 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2273 // part of the value is returned in %st0 and the imaginary part in
2274 // %st1.
2275 case ComplexX87:
2276 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002277 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002278 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002279 NULL);
2280 break;
2281 }
2282
Chris Lattnera5f58b02011-07-09 17:41:47 +00002283 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002284 switch (Hi) {
2285 // Memory was handled previously and X87 should
2286 // never occur as a hi class.
2287 case Memory:
2288 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002289 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002290
2291 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002292 case NoClass:
2293 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002294
Chris Lattner52b3c132010-09-01 00:20:33 +00002295 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002296 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002297 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2298 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002299 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002300 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002301 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002302 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2303 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002304 break;
2305
2306 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002307 // is passed in the next available eightbyte chunk if the last used
2308 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002309 //
Chris Lattner57540c52011-04-15 05:22:18 +00002310 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002311 case SSEUp:
2312 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002313 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002314 break;
2315
2316 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2317 // returned together with the previous X87 value in %st0.
2318 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002319 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002320 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002321 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002322 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002323 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002324 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002325 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2326 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002327 }
Chris Lattner31faff52010-07-28 23:06:14 +00002328 break;
2329 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002330
Chris Lattner52b3c132010-09-01 00:20:33 +00002331 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002332 // known to pass in the high eightbyte of the result. We do this by forming a
2333 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002334 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002335 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002336
Chris Lattner1f3a0632010-07-29 21:42:50 +00002337 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002338}
2339
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002340ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002341 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2342 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002343 const
2344{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002345 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002346 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002347
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002348 // Check some invariants.
2349 // FIXME: Enforce these by construction.
2350 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002351 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2352
2353 neededInt = 0;
2354 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002355 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002356 switch (Lo) {
2357 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002358 if (Hi == NoClass)
2359 return ABIArgInfo::getIgnore();
2360 // If the low part is just padding, it takes no register, leave ResType
2361 // null.
2362 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2363 "Unknown missing lo part");
2364 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002365
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002366 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2367 // on the stack.
2368 case Memory:
2369
2370 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2371 // COMPLEX_X87, it is passed in memory.
2372 case X87:
2373 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002374 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002375 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002376 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002377
2378 case SSEUp:
2379 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002380 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002381
2382 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2383 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2384 // and %r9 is used.
2385 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002386 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002387
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002388 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002389 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002390
2391 // If we have a sign or zero extended integer, make sure to return Extend
2392 // so that the parameter gets the right LLVM IR attributes.
2393 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2394 // Treat an enum type as its underlying type.
2395 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2396 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002397
Chris Lattner1f3a0632010-07-29 21:42:50 +00002398 if (Ty->isIntegralOrEnumerationType() &&
2399 Ty->isPromotableIntegerType())
2400 return ABIArgInfo::getExtend();
2401 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002402
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002403 break;
2404
2405 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2406 // available SSE register is used, the registers are taken in the
2407 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002408 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002409 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002410 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002411 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002412 break;
2413 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002414 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002415
Chris Lattnera5f58b02011-07-09 17:41:47 +00002416 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002417 switch (Hi) {
2418 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002419 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002420 // which is passed in memory.
2421 case Memory:
2422 case X87:
2423 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002424 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425
2426 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002427
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002428 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002429 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002430 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002431 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002432
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002433 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2434 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002435 break;
2436
2437 // X87Up generally doesn't occur here (long double is passed in
2438 // memory), except in situations involving unions.
2439 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002440 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002441 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002442
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002443 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2444 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002445
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002446 ++neededSSE;
2447 break;
2448
2449 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2450 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002451 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002453 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002454 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002455 break;
2456 }
2457
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002458 // If a high part was specified, merge it together with the low part. It is
2459 // known to pass in the high eightbyte of the result. We do this by forming a
2460 // first class struct aggregate with the high and low part: {low, high}
2461 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002462 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002463
Chris Lattner1f3a0632010-07-29 21:42:50 +00002464 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002465}
2466
Chris Lattner22326a12010-07-29 02:31:05 +00002467void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002468
Chris Lattner458b2aa2010-07-29 02:16:43 +00002469 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002470
2471 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002472 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002473
2474 // If the return value is indirect, then the hidden argument is consuming one
2475 // integer register.
2476 if (FI.getReturnInfo().isIndirect())
2477 --freeIntRegs;
2478
Eli Friedman96fd2642013-06-12 00:13:45 +00002479 bool isVariadic = FI.isVariadic();
2480 unsigned numRequiredArgs = 0;
2481 if (isVariadic)
2482 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2483
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002484 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2485 // get assigned (in left-to-right order) for passing as follows...
2486 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2487 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002488 bool isNamedArg = true;
2489 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002490 isNamedArg = (it - FI.arg_begin()) <
2491 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002492
Bill Wendling9987c0e2010-10-18 23:51:38 +00002493 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002494 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002495 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496
2497 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2498 // eightbyte of an argument, the whole argument is passed on the
2499 // stack. If registers have already been assigned for some
2500 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002501 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002502 freeIntRegs -= neededInt;
2503 freeSSERegs -= neededSSE;
2504 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002505 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002506 }
2507 }
2508}
2509
2510static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2511 QualType Ty,
2512 CodeGenFunction &CGF) {
2513 llvm::Value *overflow_arg_area_p =
2514 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2515 llvm::Value *overflow_arg_area =
2516 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2517
2518 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2519 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002520 // It isn't stated explicitly in the standard, but in practice we use
2521 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002522 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2523 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002524 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002525 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002526 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2528 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002529 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002530 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002531 overflow_arg_area =
2532 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2533 overflow_arg_area->getType(),
2534 "overflow_arg_area.align");
2535 }
2536
2537 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002538 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002539 llvm::Value *Res =
2540 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002541 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002542
2543 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2544 // l->overflow_arg_area + sizeof(type).
2545 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2546 // an 8 byte boundary.
2547
2548 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002549 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002550 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002551 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2552 "overflow_arg_area.next");
2553 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2554
2555 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2556 return Res;
2557}
2558
2559llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2560 CodeGenFunction &CGF) const {
2561 // Assume that va_list type is correct; should be pointer to LLVM type:
2562 // struct {
2563 // i32 gp_offset;
2564 // i32 fp_offset;
2565 // i8* overflow_arg_area;
2566 // i8* reg_save_area;
2567 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002568 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002569
Chris Lattner9723d6c2010-03-11 18:19:55 +00002570 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002571 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2572 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002573
2574 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2575 // in the registers. If not go to step 7.
2576 if (!neededInt && !neededSSE)
2577 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2578
2579 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2580 // general purpose registers needed to pass type and num_fp to hold
2581 // the number of floating point registers needed.
2582
2583 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2584 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2585 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2586 //
2587 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2588 // register save space).
2589
2590 llvm::Value *InRegs = 0;
2591 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2592 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2593 if (neededInt) {
2594 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2595 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002596 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2597 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598 }
2599
2600 if (neededSSE) {
2601 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2602 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2603 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002604 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2605 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002606 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2607 }
2608
2609 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2610 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2611 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2612 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2613
2614 // Emit code to load the value if it was passed in registers.
2615
2616 CGF.EmitBlock(InRegBlock);
2617
2618 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2619 // an offset of l->gp_offset and/or l->fp_offset. This may require
2620 // copying to a temporary location in case the parameter is passed
2621 // in different register classes or requires an alignment greater
2622 // than 8 for general purpose registers and 16 for XMM registers.
2623 //
2624 // FIXME: This really results in shameful code when we end up needing to
2625 // collect arguments from different places; often what should result in a
2626 // simple assembling of a structure from scattered addresses has many more
2627 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002628 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 llvm::Value *RegAddr =
2630 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2631 "reg_save_area");
2632 if (neededInt && neededSSE) {
2633 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002634 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002635 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002636 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2637 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002638 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002639 llvm::Type *TyLo = ST->getElementType(0);
2640 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002641 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002643 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2644 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002645 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2646 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002647 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2648 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 llvm::Value *V =
2650 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2651 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2652 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2653 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2654
Owen Anderson170229f2009-07-14 23:10:40 +00002655 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002656 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002657 } else if (neededInt) {
2658 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2659 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002660 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002661
2662 // Copy to a temporary if necessary to ensure the appropriate alignment.
2663 std::pair<CharUnits, CharUnits> SizeAlign =
2664 CGF.getContext().getTypeInfoInChars(Ty);
2665 uint64_t TySize = SizeAlign.first.getQuantity();
2666 unsigned TyAlign = SizeAlign.second.getQuantity();
2667 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002668 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2669 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2670 RegAddr = Tmp;
2671 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002672 } else if (neededSSE == 1) {
2673 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2674 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2675 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002676 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002677 assert(neededSSE == 2 && "Invalid number of needed registers!");
2678 // SSE registers are spaced 16 bytes apart in the register save
2679 // area, we need to collect the two eightbytes together.
2680 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002681 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002682 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002683 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002684 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002685 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2686 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2687 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002688 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2689 DblPtrTy));
2690 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2691 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2692 DblPtrTy));
2693 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2694 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2695 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002696 }
2697
2698 // AMD64-ABI 3.5.7p5: Step 5. Set:
2699 // l->gp_offset = l->gp_offset + num_gp * 8
2700 // l->fp_offset = l->fp_offset + num_fp * 16.
2701 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002702 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002703 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2704 gp_offset_p);
2705 }
2706 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002707 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2709 fp_offset_p);
2710 }
2711 CGF.EmitBranch(ContBlock);
2712
2713 // Emit code to load the value if it was passed in memory.
2714
2715 CGF.EmitBlock(InMemBlock);
2716 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2717
2718 // Return the appropriate result.
2719
2720 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002721 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002722 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002723 ResAddr->addIncoming(RegAddr, InRegBlock);
2724 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002725 return ResAddr;
2726}
2727
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002728ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002729
2730 if (Ty->isVoidType())
2731 return ABIArgInfo::getIgnore();
2732
2733 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2734 Ty = EnumTy->getDecl()->getIntegerType();
2735
2736 uint64_t Size = getContext().getTypeSize(Ty);
2737
2738 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002739 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002740 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002741 return ABIArgInfo::getIndirect(0, false);
2742 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002743 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002744 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2745 }
2746
2747 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002748 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2749
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002750 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002751 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002752 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2753 Size));
2754
2755 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2756 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2757 if (Size <= 64 &&
NAKAMURA Takumie03c6032011-01-19 00:11:33 +00002758 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002759 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2760 Size));
2761
2762 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2763 }
2764
2765 if (Ty->isPromotableIntegerType())
2766 return ABIArgInfo::getExtend();
2767
2768 return ABIArgInfo::getDirect();
2769}
2770
2771void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2772
2773 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002774 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002775
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002776 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2777 it != ie; ++it)
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002778 it->info = classify(it->type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002779}
2780
Chris Lattner04dc9572010-08-31 16:44:54 +00002781llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2782 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002783 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002784
Chris Lattner04dc9572010-08-31 16:44:54 +00002785 CGBuilderTy &Builder = CGF.Builder;
2786 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2787 "ap");
2788 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2789 llvm::Type *PTy =
2790 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2791 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2792
2793 uint64_t Offset =
2794 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2795 llvm::Value *NextAddr =
2796 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2797 "ap.next");
2798 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2799
2800 return AddrTyped;
2801}
Chris Lattner0cf24192010-06-28 20:05:43 +00002802
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002803namespace {
2804
Derek Schuffa2020962012-10-16 22:30:41 +00002805class NaClX86_64ABIInfo : public ABIInfo {
2806 public:
2807 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2808 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2809 virtual void computeInfo(CGFunctionInfo &FI) const;
2810 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2811 CodeGenFunction &CGF) const;
2812 private:
2813 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2814 X86_64ABIInfo NInfo; // Used for everything else.
2815};
2816
2817class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2818 public:
2819 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2820 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2821};
2822
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002823}
2824
Derek Schuffa2020962012-10-16 22:30:41 +00002825void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2826 if (FI.getASTCallingConvention() == CC_PnaclCall)
2827 PInfo.computeInfo(FI);
2828 else
2829 NInfo.computeInfo(FI);
2830}
2831
2832llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2833 CodeGenFunction &CGF) const {
2834 // Always use the native convention; calling pnacl-style varargs functions
2835 // is unuspported.
2836 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2837}
2838
2839
John McCallea8d8bb2010-03-11 00:10:12 +00002840// PowerPC-32
2841
2842namespace {
2843class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2844public:
Chris Lattner2b037972010-07-29 02:01:43 +00002845 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002846
John McCallea8d8bb2010-03-11 00:10:12 +00002847 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2848 // This is recovered from gcc output.
2849 return 1; // r1 is the dedicated stack pointer
2850 }
2851
2852 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002853 llvm::Value *Address) const;
John McCallea8d8bb2010-03-11 00:10:12 +00002854};
2855
2856}
2857
2858bool
2859PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2860 llvm::Value *Address) const {
2861 // This is calculated from the LLVM and GCC tables and verified
2862 // against gcc output. AFAIK all ABIs use the same encoding.
2863
2864 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002865
Chris Lattnerece04092012-02-07 00:39:47 +00002866 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002867 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2868 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2869 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2870
2871 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002872 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002873
2874 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002875 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002876
2877 // 64-76 are various 4-byte special-purpose registers:
2878 // 64: mq
2879 // 65: lr
2880 // 66: ctr
2881 // 67: ap
2882 // 68-75 cr0-7
2883 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002884 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002885
2886 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002887 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002888
2889 // 109: vrsave
2890 // 110: vscr
2891 // 111: spe_acc
2892 // 112: spefscr
2893 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002894 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002895
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002896 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002897}
2898
Roman Divackyd966e722012-05-09 18:22:46 +00002899// PowerPC-64
2900
2901namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002902/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2903class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2904
2905public:
2906 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2907
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002908 bool isPromotableTypeForABI(QualType Ty) const;
2909
2910 ABIArgInfo classifyReturnType(QualType RetTy) const;
2911 ABIArgInfo classifyArgumentType(QualType Ty) const;
2912
Bill Schmidt84d37792012-10-12 19:26:17 +00002913 // TODO: We can add more logic to computeInfo to improve performance.
2914 // Example: For aggregate arguments that fit in a register, we could
2915 // use getDirectInReg (as is done below for structs containing a single
2916 // floating-point value) to avoid pushing them to memory on function
2917 // entry. This would require changing the logic in PPCISelLowering
2918 // when lowering the parameters in the caller and args in the callee.
2919 virtual void computeInfo(CGFunctionInfo &FI) const {
2920 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2921 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2922 it != ie; ++it) {
2923 // We rely on the default argument classification for the most part.
2924 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002925 // or vector item must be passed in a register if one is available.
Bill Schmidt84d37792012-10-12 19:26:17 +00002926 const Type *T = isSingleElementStruct(it->type, getContext());
2927 if (T) {
2928 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002929 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002930 QualType QT(T, 0);
2931 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2932 continue;
2933 }
2934 }
2935 it->info = classifyArgumentType(it->type);
2936 }
2937 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002938
2939 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2940 QualType Ty,
2941 CodeGenFunction &CGF) const;
2942};
2943
2944class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2945public:
2946 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2947 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2948
2949 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2950 // This is recovered from gcc output.
2951 return 1; // r1 is the dedicated stack pointer
2952 }
2953
2954 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2955 llvm::Value *Address) const;
2956};
2957
Roman Divackyd966e722012-05-09 18:22:46 +00002958class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2959public:
2960 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2961
2962 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2963 // This is recovered from gcc output.
2964 return 1; // r1 is the dedicated stack pointer
2965 }
2966
2967 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2968 llvm::Value *Address) const;
2969};
2970
2971}
2972
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002973// Return true if the ABI requires Ty to be passed sign- or zero-
2974// extended to 64 bits.
2975bool
2976PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2977 // Treat an enum type as its underlying type.
2978 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2979 Ty = EnumTy->getDecl()->getIntegerType();
2980
2981 // Promotable integer types are required to be promoted by the ABI.
2982 if (Ty->isPromotableIntegerType())
2983 return true;
2984
2985 // In addition to the usual promotable integer types, we also need to
2986 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2987 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2988 switch (BT->getKind()) {
2989 case BuiltinType::Int:
2990 case BuiltinType::UInt:
2991 return true;
2992 default:
2993 break;
2994 }
2995
2996 return false;
2997}
2998
2999ABIArgInfo
3000PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003001 if (Ty->isAnyComplexType())
3002 return ABIArgInfo::getDirect();
3003
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003004 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003005 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003006 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003007
3008 return ABIArgInfo::getIndirect(0);
3009 }
3010
3011 return (isPromotableTypeForABI(Ty) ?
3012 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3013}
3014
3015ABIArgInfo
3016PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3017 if (RetTy->isVoidType())
3018 return ABIArgInfo::getIgnore();
3019
Bill Schmidta3d121c2012-12-17 04:20:17 +00003020 if (RetTy->isAnyComplexType())
3021 return ABIArgInfo::getDirect();
3022
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003023 if (isAggregateTypeForABI(RetTy))
3024 return ABIArgInfo::getIndirect(0);
3025
3026 return (isPromotableTypeForABI(RetTy) ?
3027 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3028}
3029
Bill Schmidt25cb3492012-10-03 19:18:57 +00003030// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3031llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3032 QualType Ty,
3033 CodeGenFunction &CGF) const {
3034 llvm::Type *BP = CGF.Int8PtrTy;
3035 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3036
3037 CGBuilderTy &Builder = CGF.Builder;
3038 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3039 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3040
Bill Schmidt924c4782013-01-14 17:45:36 +00003041 // Update the va_list pointer. The pointer should be bumped by the
3042 // size of the object. We can trust getTypeSize() except for a complex
3043 // type whose base type is smaller than a doubleword. For these, the
3044 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003045 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003046 QualType BaseTy;
3047 unsigned CplxBaseSize = 0;
3048
3049 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3050 BaseTy = CTy->getElementType();
3051 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3052 if (CplxBaseSize < 8)
3053 SizeInBytes = 16;
3054 }
3055
Bill Schmidt25cb3492012-10-03 19:18:57 +00003056 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3057 llvm::Value *NextAddr =
3058 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3059 "ap.next");
3060 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3061
Bill Schmidt924c4782013-01-14 17:45:36 +00003062 // If we have a complex type and the base type is smaller than 8 bytes,
3063 // the ABI calls for the real and imaginary parts to be right-adjusted
3064 // in separate doublewords. However, Clang expects us to produce a
3065 // pointer to a structure with the two parts packed tightly. So generate
3066 // loads of the real and imaginary parts relative to the va_list pointer,
3067 // and store them to a temporary structure.
3068 if (CplxBaseSize && CplxBaseSize < 8) {
3069 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3070 llvm::Value *ImagAddr = RealAddr;
3071 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3072 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3073 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3074 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3075 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3076 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3077 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3078 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3079 "vacplx");
3080 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3081 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3082 Builder.CreateStore(Real, RealPtr, false);
3083 Builder.CreateStore(Imag, ImagPtr, false);
3084 return Ptr;
3085 }
3086
Bill Schmidt25cb3492012-10-03 19:18:57 +00003087 // If the argument is smaller than 8 bytes, it is right-adjusted in
3088 // its doubleword slot. Adjust the pointer to pick it up from the
3089 // correct offset.
3090 if (SizeInBytes < 8) {
3091 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3092 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3093 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3094 }
3095
3096 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3097 return Builder.CreateBitCast(Addr, PTy);
3098}
3099
3100static bool
3101PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3102 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003103 // This is calculated from the LLVM and GCC tables and verified
3104 // against gcc output. AFAIK all ABIs use the same encoding.
3105
3106 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3107
3108 llvm::IntegerType *i8 = CGF.Int8Ty;
3109 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3110 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3111 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3112
3113 // 0-31: r0-31, the 8-byte general-purpose registers
3114 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3115
3116 // 32-63: fp0-31, the 8-byte floating-point registers
3117 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3118
3119 // 64-76 are various 4-byte special-purpose registers:
3120 // 64: mq
3121 // 65: lr
3122 // 66: ctr
3123 // 67: ap
3124 // 68-75 cr0-7
3125 // 76: xer
3126 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3127
3128 // 77-108: v0-31, the 16-byte vector registers
3129 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3130
3131 // 109: vrsave
3132 // 110: vscr
3133 // 111: spe_acc
3134 // 112: spefscr
3135 // 113: sfp
3136 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3137
3138 return false;
3139}
John McCallea8d8bb2010-03-11 00:10:12 +00003140
Bill Schmidt25cb3492012-10-03 19:18:57 +00003141bool
3142PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3143 CodeGen::CodeGenFunction &CGF,
3144 llvm::Value *Address) const {
3145
3146 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3147}
3148
3149bool
3150PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3151 llvm::Value *Address) const {
3152
3153 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3154}
3155
Chris Lattner0cf24192010-06-28 20:05:43 +00003156//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003157// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003158//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003159
3160namespace {
3161
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003162class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003163public:
3164 enum ABIKind {
3165 APCS = 0,
3166 AAPCS = 1,
3167 AAPCS_VFP
3168 };
3169
3170private:
3171 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00003172 mutable int VFPRegs[16];
3173 const unsigned NumVFPs;
3174 const unsigned NumGPRs;
3175 mutable unsigned AllocatedGPRs;
3176 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003177
3178public:
Oliver Stannard405bded2014-02-11 09:25:50 +00003179 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
3180 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00003181 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003182 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00003183 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003184
John McCall3480ef22011-08-30 01:42:09 +00003185 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003186 switch (getTarget().getTriple().getEnvironment()) {
3187 case llvm::Triple::Android:
3188 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003189 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003190 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003191 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003192 return true;
3193 default:
3194 return false;
3195 }
John McCall3480ef22011-08-30 01:42:09 +00003196 }
3197
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003198 bool isEABIHF() const {
3199 switch (getTarget().getTriple().getEnvironment()) {
3200 case llvm::Triple::EABIHF:
3201 case llvm::Triple::GNUEABIHF:
3202 return true;
3203 default:
3204 return false;
3205 }
3206 }
3207
Daniel Dunbar020daa92009-09-12 01:00:39 +00003208 ABIKind getABIKind() const { return Kind; }
3209
Tim Northovera484bc02013-10-01 14:34:25 +00003210private:
Amara Emerson9dc78782014-01-28 10:56:36 +00003211 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Oliver Stannard405bded2014-02-11 09:25:50 +00003212 ABIArgInfo classifyArgumentType(QualType RetTy, bool &IsHA, bool isVariadic,
3213 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00003214 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003215
Chris Lattner22326a12010-07-29 02:31:05 +00003216 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003217
3218 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3219 CodeGenFunction &CGF) const;
John McCall882987f2013-02-28 19:01:20 +00003220
3221 llvm::CallingConv::ID getLLVMDefaultCC() const;
3222 llvm::CallingConv::ID getABIDefaultCC() const;
3223 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003224
3225 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
3226 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
3227 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003228};
3229
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003230class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3231public:
Chris Lattner2b037972010-07-29 02:01:43 +00003232 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3233 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003234
John McCall3480ef22011-08-30 01:42:09 +00003235 const ARMABIInfo &getABIInfo() const {
3236 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3237 }
3238
John McCallbeec5a02010-03-06 00:35:14 +00003239 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3240 return 13;
3241 }
Roman Divackyc1617352011-05-18 19:36:54 +00003242
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003243 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCall31168b02011-06-15 23:02:42 +00003244 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3245 }
3246
Roman Divackyc1617352011-05-18 19:36:54 +00003247 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3248 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003249 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003250
3251 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003252 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003253 return false;
3254 }
John McCall3480ef22011-08-30 01:42:09 +00003255
3256 unsigned getSizeOfUnwindException() const {
3257 if (getABIInfo().isEABI()) return 88;
3258 return TargetCodeGenInfo::getSizeOfUnwindException();
3259 }
Tim Northovera484bc02013-10-01 14:34:25 +00003260
3261 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3262 CodeGen::CodeGenModule &CGM) const {
3263 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3264 if (!FD)
3265 return;
3266
3267 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3268 if (!Attr)
3269 return;
3270
3271 const char *Kind;
3272 switch (Attr->getInterrupt()) {
3273 case ARMInterruptAttr::Generic: Kind = ""; break;
3274 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3275 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3276 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3277 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3278 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3279 }
3280
3281 llvm::Function *Fn = cast<llvm::Function>(GV);
3282
3283 Fn->addFnAttr("interrupt", Kind);
3284
3285 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3286 return;
3287
3288 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3289 // however this is not necessarily true on taking any interrupt. Instruct
3290 // the backend to perform a realignment as part of the function prologue.
3291 llvm::AttrBuilder B;
3292 B.addStackAlignmentAttr(8);
3293 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3294 llvm::AttributeSet::get(CGM.getLLVMContext(),
3295 llvm::AttributeSet::FunctionIndex,
3296 B));
3297 }
3298
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003299};
3300
Daniel Dunbard59655c2009-09-12 00:59:49 +00003301}
3302
Chris Lattner22326a12010-07-29 02:31:05 +00003303void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003304 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003305 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003306 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3307 // VFP registers of the appropriate type unallocated then the argument is
3308 // allocated to the lowest-numbered sequence of such registers.
3309 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3310 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00003311 resetAllocatedRegs();
3312
Amara Emerson9dc78782014-01-28 10:56:36 +00003313 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003314 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Ren2a523d82012-10-30 23:21:41 +00003315 it != ie; ++it) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003316 unsigned PreAllocationVFPs = AllocatedVFPs;
3317 unsigned PreAllocationGPRs = AllocatedGPRs;
Manman Ren2a523d82012-10-30 23:21:41 +00003318 bool IsHA = false;
Oliver Stannard405bded2014-02-11 09:25:50 +00003319 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00003320 // 6.1.2.3 There is one VFP co-processor register class using registers
3321 // s0-s15 (d0-d7) for passing arguments.
Oliver Stannard405bded2014-02-11 09:25:50 +00003322 it->info = classifyArgumentType(it->type, IsHA, FI.isVariadic(), IsCPRC);
3323 assert((IsCPRC || !IsHA) && "Homogeneous aggregates must be CPRCs");
Manman Ren2a523d82012-10-30 23:21:41 +00003324 // If we do not have enough VFP registers for the HA, any VFP registers
3325 // that are unallocated are marked as unavailable. To achieve this, we add
Oliver Stannard405bded2014-02-11 09:25:50 +00003326 // padding of (NumVFPs - PreAllocationVFP) floats.
Amara Emerson9dc78782014-01-28 10:56:36 +00003327 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3328 // and the callee is not variadic.
Oliver Stannard405bded2014-02-11 09:25:50 +00003329 if (IsHA && AllocatedVFPs > NumVFPs && PreAllocationVFPs < NumVFPs) {
Manman Ren2a523d82012-10-30 23:21:41 +00003330 llvm::Type *PaddingTy = llvm::ArrayType::get(
Oliver Stannard405bded2014-02-11 09:25:50 +00003331 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocationVFPs);
3332 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3333 }
3334
3335 // If we have allocated some arguments onto the stack (due to running
3336 // out of VFP registers), we cannot split an argument between GPRs and
3337 // the stack. If this situation occurs, we add padding to prevent the
3338 // GPRs from being used. In this situiation, the current argument could
3339 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
3340 // unusable anyway.
3341 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
3342 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) {
3343 llvm::Type *PaddingTy = llvm::ArrayType::get(
3344 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Manman Ren2a523d82012-10-30 23:21:41 +00003345 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3346 }
3347 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003348
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003349 // Always honor user-specified calling convention.
3350 if (FI.getCallingConvention() != llvm::CallingConv::C)
3351 return;
3352
John McCall882987f2013-02-28 19:01:20 +00003353 llvm::CallingConv::ID cc = getRuntimeCC();
3354 if (cc != llvm::CallingConv::C)
3355 FI.setEffectiveCallingConvention(cc);
3356}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003357
John McCall882987f2013-02-28 19:01:20 +00003358/// Return the default calling convention that LLVM will use.
3359llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3360 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003361 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003362 return llvm::CallingConv::ARM_AAPCS_VFP;
3363 else if (isEABI())
3364 return llvm::CallingConv::ARM_AAPCS;
3365 else
3366 return llvm::CallingConv::ARM_APCS;
3367}
3368
3369/// Return the calling convention that our ABI would like us to use
3370/// as the C calling convention.
3371llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003372 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003373 case APCS: return llvm::CallingConv::ARM_APCS;
3374 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3375 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003376 }
John McCall882987f2013-02-28 19:01:20 +00003377 llvm_unreachable("bad ABI kind");
3378}
3379
3380void ARMABIInfo::setRuntimeCC() {
3381 assert(getRuntimeCC() == llvm::CallingConv::C);
3382
3383 // Don't muddy up the IR with a ton of explicit annotations if
3384 // they'd just match what LLVM will infer from the triple.
3385 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3386 if (abiCC != getLLVMDefaultCC())
3387 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003388}
3389
Bob Wilsone826a2a2011-08-03 05:58:22 +00003390/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3391/// aggregate. If HAMembers is non-null, the number of base elements
3392/// contained in the type is returned through it; this is used for the
3393/// recursive calls that check aggregate component types.
3394static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3395 ASTContext &Context,
3396 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003397 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003398 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3399 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3400 return false;
3401 Members *= AT->getSize().getZExtValue();
3402 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3403 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003404 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003405 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003406
Bob Wilsone826a2a2011-08-03 05:58:22 +00003407 Members = 0;
3408 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3409 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003410 const FieldDecl *FD = *i;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003411 uint64_t FldMembers;
3412 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3413 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003414
3415 Members = (RD->isUnion() ?
3416 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003417 }
3418 } else {
3419 Members = 1;
3420 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3421 Members = 2;
3422 Ty = CT->getElementType();
3423 }
3424
3425 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3426 // double, or 64-bit or 128-bit vectors.
3427 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3428 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003429 BT->getKind() != BuiltinType::Double &&
3430 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003431 return false;
3432 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3433 unsigned VecSize = Context.getTypeSize(VT);
3434 if (VecSize != 64 && VecSize != 128)
3435 return false;
3436 } else {
3437 return false;
3438 }
3439
3440 // The base type must be the same for all members. Vector types of the
3441 // same total size are treated as being equivalent here.
3442 const Type *TyPtr = Ty.getTypePtr();
3443 if (!Base)
3444 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00003445
3446 if (Base != TyPtr) {
3447 // Homogeneous aggregates are defined as containing members with the
3448 // same machine type. There are two cases in which two members have
3449 // different TypePtrs but the same machine type:
3450
3451 // 1) Vectors of the same length, regardless of the type and number
3452 // of their members.
3453 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
3454 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3455
3456 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
3457 // machine type. This is not the case for the 64-bit AAPCS.
3458 const bool SameSizeDoubles =
3459 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
3460 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
3461 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
3462 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
3463 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3464
3465 if (!SameLengthVectors && !SameSizeDoubles)
3466 return false;
3467 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003468 }
3469
3470 // Homogeneous Aggregates can have at most 4 members of the base type.
3471 if (HAMembers)
3472 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003473
3474 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003475}
3476
Manman Renb505d332012-10-31 19:02:26 +00003477/// markAllocatedVFPs - update VFPRegs according to the alignment and
3478/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00003479void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
3480 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00003481 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00003482 if (AllocatedVFPs >= 16) {
3483 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
3484 // the stack.
3485 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00003486 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00003487 }
Manman Renb505d332012-10-31 19:02:26 +00003488 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3489 // VFP registers of the appropriate type unallocated then the argument is
3490 // allocated to the lowest-numbered sequence of such registers.
3491 for (unsigned I = 0; I < 16; I += Alignment) {
3492 bool FoundSlot = true;
3493 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3494 if (J >= 16 || VFPRegs[J]) {
3495 FoundSlot = false;
3496 break;
3497 }
3498 if (FoundSlot) {
3499 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3500 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00003501 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00003502 return;
3503 }
3504 }
3505 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3506 // unallocated are marked as unavailable.
3507 for (unsigned I = 0; I < 16; I++)
3508 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00003509 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00003510}
3511
Oliver Stannard405bded2014-02-11 09:25:50 +00003512/// Update AllocatedGPRs to record the number of general purpose registers
3513/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
3514/// this represents arguments being stored on the stack.
3515void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
3516 unsigned NumRequired) const {
3517 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
3518
3519 if (Alignment == 2 && AllocatedGPRs & 0x1)
3520 AllocatedGPRs += 1;
3521
3522 AllocatedGPRs += NumRequired;
3523}
3524
3525void ARMABIInfo::resetAllocatedRegs(void) const {
3526 AllocatedGPRs = 0;
3527 AllocatedVFPs = 0;
3528 for (unsigned i = 0; i < NumVFPs; ++i)
3529 VFPRegs[i] = 0;
3530}
3531
3532ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool &IsHA,
3533 bool isVariadic,
3534 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003535 // We update number of allocated VFPs according to
3536 // 6.1.2.1 The following argument types are VFP CPRCs:
3537 // A single-precision floating-point type (including promoted
3538 // half-precision types); A double-precision floating-point type;
3539 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3540 // with a Base Type of a single- or double-precision floating-point type,
3541 // 64-bit containerized vectors or 128-bit containerized vectors with one
3542 // to four Elements.
3543
Manman Renfef9e312012-10-16 19:18:39 +00003544 // Handle illegal vector types here.
3545 if (isIllegalVectorType(Ty)) {
3546 uint64_t Size = getContext().getTypeSize(Ty);
3547 if (Size <= 32) {
3548 llvm::Type *ResType =
3549 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00003550 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00003551 return ABIArgInfo::getDirect(ResType);
3552 }
3553 if (Size == 64) {
3554 llvm::Type *ResType = llvm::VectorType::get(
3555 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00003556 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
3557 markAllocatedGPRs(2, 2);
3558 } else {
3559 markAllocatedVFPs(2, 2);
3560 IsCPRC = true;
3561 }
Manman Renfef9e312012-10-16 19:18:39 +00003562 return ABIArgInfo::getDirect(ResType);
3563 }
3564 if (Size == 128) {
3565 llvm::Type *ResType = llvm::VectorType::get(
3566 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00003567 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
3568 markAllocatedGPRs(2, 4);
3569 } else {
3570 markAllocatedVFPs(4, 4);
3571 IsCPRC = true;
3572 }
Manman Renfef9e312012-10-16 19:18:39 +00003573 return ABIArgInfo::getDirect(ResType);
3574 }
Oliver Stannard405bded2014-02-11 09:25:50 +00003575 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00003576 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3577 }
Manman Renb505d332012-10-31 19:02:26 +00003578 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00003579 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
3580 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3581 uint64_t Size = getContext().getTypeSize(VT);
3582 // Size of a legal vector should be power of 2 and above 64.
3583 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
3584 IsCPRC = true;
3585 }
Manman Ren2a523d82012-10-30 23:21:41 +00003586 }
Manman Renb505d332012-10-31 19:02:26 +00003587 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00003588 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
3589 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3590 if (BT->getKind() == BuiltinType::Half ||
3591 BT->getKind() == BuiltinType::Float) {
3592 markAllocatedVFPs(1, 1);
3593 IsCPRC = true;
3594 }
3595 if (BT->getKind() == BuiltinType::Double ||
3596 BT->getKind() == BuiltinType::LongDouble) {
3597 markAllocatedVFPs(2, 2);
3598 IsCPRC = true;
3599 }
3600 }
Manman Ren2a523d82012-10-30 23:21:41 +00003601 }
Manman Renfef9e312012-10-16 19:18:39 +00003602
John McCalla1dee5302010-08-22 10:59:02 +00003603 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003604 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00003605 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003606 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00003607 }
Douglas Gregora71cc152010-02-02 20:10:50 +00003608
Oliver Stannard405bded2014-02-11 09:25:50 +00003609 unsigned Size = getContext().getTypeSize(Ty);
3610 if (!IsCPRC)
3611 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003612 return (Ty->isPromotableIntegerType() ?
3613 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003614 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003615
Oliver Stannard405bded2014-02-11 09:25:50 +00003616 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
3617 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00003618 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00003619 }
Tim Northover1060eae2013-06-21 22:49:34 +00003620
Daniel Dunbar09d33622009-09-14 21:54:03 +00003621 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003622 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003623 return ABIArgInfo::getIgnore();
3624
Amara Emerson9dc78782014-01-28 10:56:36 +00003625 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00003626 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3627 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003628 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003629 uint64_t Members = 0;
3630 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003631 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003632 // Base can be a floating-point or a vector.
3633 if (Base->isVectorType()) {
3634 // ElementSize is in number of floats.
3635 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00003636 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00003637 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003638 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00003639 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003640 else {
3641 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3642 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00003643 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003644 }
3645 IsHA = true;
Oliver Stannard405bded2014-02-11 09:25:50 +00003646 IsCPRC = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003647 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003648 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003649 }
3650
Manman Ren6c30e132012-08-13 21:23:55 +00003651 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003652 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3653 // most 8-byte. We realign the indirect argument if type alignment is bigger
3654 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003655 uint64_t ABIAlign = 4;
3656 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3657 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3658 getABIKind() == ARMABIInfo::AAPCS)
3659 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003660 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003661 // Update Allocated GPRs
3662 markAllocatedGPRs(1, 1);
Manman Ren8cd99812012-11-06 04:58:01 +00003663 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003664 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003665 }
3666
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003667 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003668 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003669 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003670 // FIXME: Try to match the types of the arguments more accurately where
3671 // we can.
3672 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003673 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3674 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00003675 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00003676 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003677 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3678 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00003679 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003680 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003681
Chris Lattnera5f58b02011-07-09 17:41:47 +00003682 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003683 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003684 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003685}
3686
Chris Lattner458b2aa2010-07-29 02:16:43 +00003687static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003688 llvm::LLVMContext &VMContext) {
3689 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3690 // is called integer-like if its size is less than or equal to one word, and
3691 // the offset of each of its addressable sub-fields is zero.
3692
3693 uint64_t Size = Context.getTypeSize(Ty);
3694
3695 // Check that the type fits in a word.
3696 if (Size > 32)
3697 return false;
3698
3699 // FIXME: Handle vector types!
3700 if (Ty->isVectorType())
3701 return false;
3702
Daniel Dunbard53bac72009-09-14 02:20:34 +00003703 // Float types are never treated as "integer like".
3704 if (Ty->isRealFloatingType())
3705 return false;
3706
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003707 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003708 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003709 return true;
3710
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003711 // Small complex integer types are "integer like".
3712 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3713 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003714
3715 // Single element and zero sized arrays should be allowed, by the definition
3716 // above, but they are not.
3717
3718 // Otherwise, it must be a record type.
3719 const RecordType *RT = Ty->getAs<RecordType>();
3720 if (!RT) return false;
3721
3722 // Ignore records with flexible arrays.
3723 const RecordDecl *RD = RT->getDecl();
3724 if (RD->hasFlexibleArrayMember())
3725 return false;
3726
3727 // Check that all sub-fields are at offset 0, and are themselves "integer
3728 // like".
3729 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3730
3731 bool HadField = false;
3732 unsigned idx = 0;
3733 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3734 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003735 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003736
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003737 // Bit-fields are not addressable, we only need to verify they are "integer
3738 // like". We still have to disallow a subsequent non-bitfield, for example:
3739 // struct { int : 0; int x }
3740 // is non-integer like according to gcc.
3741 if (FD->isBitField()) {
3742 if (!RD->isUnion())
3743 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003744
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003745 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3746 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003747
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003748 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003749 }
3750
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003751 // Check if this field is at offset 0.
3752 if (Layout.getFieldOffset(idx) != 0)
3753 return false;
3754
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003755 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3756 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003757
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003758 // Only allow at most one field in a structure. This doesn't match the
3759 // wording above, but follows gcc in situations with a field following an
3760 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003761 if (!RD->isUnion()) {
3762 if (HadField)
3763 return false;
3764
3765 HadField = true;
3766 }
3767 }
3768
3769 return true;
3770}
3771
Oliver Stannard405bded2014-02-11 09:25:50 +00003772ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
3773 bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003774 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003775 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003776
Daniel Dunbar19964db2010-09-23 01:54:32 +00003777 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00003778 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
3779 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00003780 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00003781 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00003782
John McCalla1dee5302010-08-22 10:59:02 +00003783 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003784 // Treat an enum type as its underlying type.
3785 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3786 RetTy = EnumTy->getDecl()->getIntegerType();
3787
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003788 return (RetTy->isPromotableIntegerType() ?
3789 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003790 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003791
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003792 // Structures with either a non-trivial destructor or a non-trivial
3793 // copy constructor are always indirect.
Oliver Stannard405bded2014-02-11 09:25:50 +00003794 if (isRecordReturnIndirect(RetTy, getCXXABI())) {
3795 markAllocatedGPRs(1, 1);
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003796 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Oliver Stannard405bded2014-02-11 09:25:50 +00003797 }
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003798
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003799 // Are we following APCS?
3800 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003801 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003802 return ABIArgInfo::getIgnore();
3803
Daniel Dunbareedf1512010-02-01 23:31:19 +00003804 // Complex types are all returned as packed integers.
3805 //
3806 // FIXME: Consider using 2 x vector types if the back end handles them
3807 // correctly.
3808 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003809 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003810 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003811
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003812 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003813 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003814 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003815 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003816 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003817 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003818 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003819 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3820 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003821 }
3822
3823 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00003824 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003825 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003826 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003827
3828 // Otherwise this is an AAPCS variant.
3829
Chris Lattner458b2aa2010-07-29 02:16:43 +00003830 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003831 return ABIArgInfo::getIgnore();
3832
Bob Wilson1d9269a2011-11-02 04:51:36 +00003833 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00003834 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson1d9269a2011-11-02 04:51:36 +00003835 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003836 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3837 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003838 // Homogeneous Aggregates are returned directly.
3839 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003840 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003841 }
3842
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003843 // Aggregates <= 4 bytes are returned in r0; other aggregates
3844 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003845 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003846 if (Size <= 32) {
3847 // Return in the smallest viable integer type.
3848 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003849 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003850 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003851 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3852 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003853 }
3854
Oliver Stannard405bded2014-02-11 09:25:50 +00003855 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003856 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003857}
3858
Manman Renfef9e312012-10-16 19:18:39 +00003859/// isIllegalVector - check whether Ty is an illegal vector type.
3860bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3861 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3862 // Check whether VT is legal.
3863 unsigned NumElements = VT->getNumElements();
3864 uint64_t Size = getContext().getTypeSize(VT);
3865 // NumElements should be power of 2.
3866 if ((NumElements & (NumElements - 1)) != 0)
3867 return true;
3868 // Size should be greater than 32 bits.
3869 return Size <= 32;
3870 }
3871 return false;
3872}
3873
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003874llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003875 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003876 llvm::Type *BP = CGF.Int8PtrTy;
3877 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003878
3879 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003880 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003881 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003882
Tim Northover1711cc92013-06-21 23:05:33 +00003883 if (isEmptyRecord(getContext(), Ty, true)) {
3884 // These are ignored for parameter passing purposes.
3885 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3886 return Builder.CreateBitCast(Addr, PTy);
3887 }
3888
Manman Rencca54d02012-10-16 19:01:37 +00003889 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003890 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003891 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003892
3893 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3894 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003895 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3896 getABIKind() == ARMABIInfo::AAPCS)
3897 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3898 else
3899 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003900 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3901 if (isIllegalVectorType(Ty) && Size > 16) {
3902 IsIndirect = true;
3903 Size = 4;
3904 TyAlign = 4;
3905 }
Manman Rencca54d02012-10-16 19:01:37 +00003906
3907 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003908 if (TyAlign > 4) {
3909 assert((TyAlign & (TyAlign - 1)) == 0 &&
3910 "Alignment is not power of 2!");
3911 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3912 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3913 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003914 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003915 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003916
3917 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003918 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003919 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003920 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003921 "ap.next");
3922 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3923
Manman Renfef9e312012-10-16 19:18:39 +00003924 if (IsIndirect)
3925 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003926 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003927 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3928 // may not be correctly aligned for the vector type. We create an aligned
3929 // temporary space and copy the content over from ap.cur to the temporary
3930 // space. This is necessary if the natural alignment of the type is greater
3931 // than the ABI alignment.
3932 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3933 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3934 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3935 "var.align");
3936 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3937 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3938 Builder.CreateMemCpy(Dst, Src,
3939 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3940 TyAlign, false);
3941 Addr = AlignedTemp; //The content is in aligned location.
3942 }
3943 llvm::Type *PTy =
3944 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3945 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3946
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003947 return AddrTyped;
3948}
3949
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003950namespace {
3951
Derek Schuffa2020962012-10-16 22:30:41 +00003952class NaClARMABIInfo : public ABIInfo {
3953 public:
3954 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3955 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3956 virtual void computeInfo(CGFunctionInfo &FI) const;
3957 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3958 CodeGenFunction &CGF) const;
3959 private:
3960 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3961 ARMABIInfo NInfo; // Used for everything else.
3962};
3963
3964class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3965 public:
3966 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3967 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3968};
3969
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003970}
3971
Derek Schuffa2020962012-10-16 22:30:41 +00003972void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3973 if (FI.getASTCallingConvention() == CC_PnaclCall)
3974 PInfo.computeInfo(FI);
3975 else
3976 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3977}
3978
3979llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3980 CodeGenFunction &CGF) const {
3981 // Always use the native convention; calling pnacl-style varargs functions
3982 // is unsupported.
3983 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3984}
3985
Chris Lattner0cf24192010-06-28 20:05:43 +00003986//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003987// AArch64 ABI Implementation
3988//===----------------------------------------------------------------------===//
3989
3990namespace {
3991
3992class AArch64ABIInfo : public ABIInfo {
3993public:
3994 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3995
3996private:
3997 // The AArch64 PCS is explicit about return types and argument types being
3998 // handled identically, so we don't need to draw a distinction between
3999 // Argument and Return classification.
4000 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
4001 int &FreeVFPRegs) const;
4002
4003 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
4004 llvm::Type *DirectTy = 0) const;
4005
4006 virtual void computeInfo(CGFunctionInfo &FI) const;
4007
4008 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4009 CodeGenFunction &CGF) const;
4010};
4011
4012class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4013public:
4014 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
4015 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
4016
4017 const AArch64ABIInfo &getABIInfo() const {
4018 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
4019 }
4020
4021 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
4022 return 31;
4023 }
4024
4025 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4026 llvm::Value *Address) const {
4027 // 0-31 are x0-x30 and sp: 8 bytes each
4028 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
4029 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
4030
4031 // 64-95 are v0-v31: 16 bytes each
4032 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
4033 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
4034
4035 return false;
4036 }
4037
4038};
4039
4040}
4041
4042void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4043 int FreeIntRegs = 8, FreeVFPRegs = 8;
4044
4045 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
4046 FreeIntRegs, FreeVFPRegs);
4047
4048 FreeIntRegs = FreeVFPRegs = 8;
4049 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4050 it != ie; ++it) {
4051 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
4052
4053 }
4054}
4055
4056ABIArgInfo
4057AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
4058 bool IsInt, llvm::Type *DirectTy) const {
4059 if (FreeRegs >= RegsNeeded) {
4060 FreeRegs -= RegsNeeded;
4061 return ABIArgInfo::getDirect(DirectTy);
4062 }
4063
4064 llvm::Type *Padding = 0;
4065
4066 // We need padding so that later arguments don't get filled in anyway. That
4067 // wouldn't happen if only ByVal arguments followed in the same category, but
4068 // a large structure will simply seem to be a pointer as far as LLVM is
4069 // concerned.
4070 if (FreeRegs > 0) {
4071 if (IsInt)
4072 Padding = llvm::Type::getInt64Ty(getVMContext());
4073 else
4074 Padding = llvm::Type::getFloatTy(getVMContext());
4075
4076 // Either [N x i64] or [N x float].
4077 Padding = llvm::ArrayType::get(Padding, FreeRegs);
4078 FreeRegs = 0;
4079 }
4080
4081 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
4082 /*IsByVal=*/ true, /*Realign=*/ false,
4083 Padding);
4084}
4085
4086
4087ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
4088 int &FreeIntRegs,
4089 int &FreeVFPRegs) const {
4090 // Can only occurs for return, but harmless otherwise.
4091 if (Ty->isVoidType())
4092 return ABIArgInfo::getIgnore();
4093
4094 // Large vector types should be returned via memory. There's no such concept
4095 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
4096 // classified they'd go into memory (see B.3).
4097 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
4098 if (FreeIntRegs > 0)
4099 --FreeIntRegs;
4100 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4101 }
4102
4103 // All non-aggregate LLVM types have a concrete ABI representation so they can
4104 // be passed directly. After this block we're guaranteed to be in a
4105 // complicated case.
4106 if (!isAggregateTypeForABI(Ty)) {
4107 // Treat an enum type as its underlying type.
4108 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4109 Ty = EnumTy->getDecl()->getIntegerType();
4110
4111 if (Ty->isFloatingType() || Ty->isVectorType())
4112 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
4113
4114 assert(getContext().getTypeSize(Ty) <= 128 &&
4115 "unexpectedly large scalar type");
4116
4117 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
4118
4119 // If the type may need padding registers to ensure "alignment", we must be
4120 // careful when this is accounted for. Increasing the effective size covers
4121 // all cases.
4122 if (getContext().getTypeAlign(Ty) == 128)
4123 RegsNeeded += FreeIntRegs % 2 != 0;
4124
4125 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
4126 }
4127
Mark Lacey3825e832013-10-06 01:33:34 +00004128 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004129 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00004130 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004131 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00004132 }
4133
4134 if (isEmptyRecord(getContext(), Ty, true)) {
4135 if (!getContext().getLangOpts().CPlusPlus) {
4136 // Empty structs outside C++ mode are a GNU extension, so no ABI can
4137 // possibly tell us what to do. It turns out (I believe) that GCC ignores
4138 // the object for parameter-passsing purposes.
4139 return ABIArgInfo::getIgnore();
4140 }
4141
4142 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
4143 // description of va_arg in the PCS require that an empty struct does
4144 // actually occupy space for parameter-passing. I'm hoping for a
4145 // clarification giving an explicit paragraph to point to in future.
4146 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
4147 llvm::Type::getInt8Ty(getVMContext()));
4148 }
4149
4150 // Homogeneous vector aggregates get passed in registers or on the stack.
4151 const Type *Base = 0;
4152 uint64_t NumMembers = 0;
4153 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
4154 assert(Base && "Base class should be set for homogeneous aggregate");
4155 // Homogeneous aggregates are passed and returned directly.
4156 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
4157 /*IsInt=*/ false);
4158 }
4159
4160 uint64_t Size = getContext().getTypeSize(Ty);
4161 if (Size <= 128) {
4162 // Small structs can use the same direct type whether they're in registers
4163 // or on the stack.
4164 llvm::Type *BaseTy;
4165 unsigned NumBases;
4166 int SizeInRegs = (Size + 63) / 64;
4167
4168 if (getContext().getTypeAlign(Ty) == 128) {
4169 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
4170 NumBases = 1;
4171
4172 // If the type may need padding registers to ensure "alignment", we must
4173 // be careful when this is accounted for. Increasing the effective size
4174 // covers all cases.
4175 SizeInRegs += FreeIntRegs % 2 != 0;
4176 } else {
4177 BaseTy = llvm::Type::getInt64Ty(getVMContext());
4178 NumBases = SizeInRegs;
4179 }
4180 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
4181
4182 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
4183 /*IsInt=*/ true, DirectTy);
4184 }
4185
4186 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
4187 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
4188 --FreeIntRegs;
4189 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
4190}
4191
4192llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4193 CodeGenFunction &CGF) const {
4194 // The AArch64 va_list type and handling is specified in the Procedure Call
4195 // Standard, section B.4:
4196 //
4197 // struct {
4198 // void *__stack;
4199 // void *__gr_top;
4200 // void *__vr_top;
4201 // int __gr_offs;
4202 // int __vr_offs;
4203 // };
4204
4205 assert(!CGF.CGM.getDataLayout().isBigEndian()
4206 && "va_arg not implemented for big-endian AArch64");
4207
4208 int FreeIntRegs = 8, FreeVFPRegs = 8;
4209 Ty = CGF.getContext().getCanonicalType(Ty);
4210 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4211
4212 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4213 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4214 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4215 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4216
4217 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4218 int reg_top_index;
4219 int RegSize;
4220 if (FreeIntRegs < 8) {
4221 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4222 // 3 is the field number of __gr_offs
4223 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4224 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4225 reg_top_index = 1; // field number for __gr_top
4226 RegSize = 8 * (8 - FreeIntRegs);
4227 } else {
4228 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4229 // 4 is the field number of __vr_offs.
4230 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4231 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4232 reg_top_index = 2; // field number for __vr_top
4233 RegSize = 16 * (8 - FreeVFPRegs);
4234 }
4235
4236 //=======================================
4237 // Find out where argument was passed
4238 //=======================================
4239
4240 // If reg_offs >= 0 we're already using the stack for this type of
4241 // argument. We don't want to keep updating reg_offs (in case it overflows,
4242 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4243 // whatever they get).
4244 llvm::Value *UsingStack = 0;
4245 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4246 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4247
4248 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4249
4250 // Otherwise, at least some kind of argument could go in these registers, the
4251 // quesiton is whether this particular type is too big.
4252 CGF.EmitBlock(MaybeRegBlock);
4253
4254 // Integer arguments may need to correct register alignment (for example a
4255 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4256 // align __gr_offs to calculate the potential address.
4257 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4258 int Align = getContext().getTypeAlign(Ty) / 8;
4259
4260 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4261 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4262 "align_regoffs");
4263 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4264 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4265 "aligned_regoffs");
4266 }
4267
4268 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4269 llvm::Value *NewOffset = 0;
4270 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4271 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4272 "new_reg_offs");
4273 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4274
4275 // Now we're in a position to decide whether this argument really was in
4276 // registers or not.
4277 llvm::Value *InRegs = 0;
4278 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4279 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4280 "inreg");
4281
4282 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4283
4284 //=======================================
4285 // Argument was in registers
4286 //=======================================
4287
4288 // Now we emit the code for if the argument was originally passed in
4289 // registers. First start the appropriate block:
4290 CGF.EmitBlock(InRegBlock);
4291
4292 llvm::Value *reg_top_p = 0, *reg_top = 0;
4293 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4294 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4295 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4296 llvm::Value *RegAddr = 0;
4297 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4298
4299 if (!AI.isDirect()) {
4300 // If it's been passed indirectly (actually a struct), whatever we find from
4301 // stored registers or on the stack will actually be a struct **.
4302 MemTy = llvm::PointerType::getUnqual(MemTy);
4303 }
4304
4305 const Type *Base = 0;
4306 uint64_t NumMembers;
4307 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4308 && NumMembers > 1) {
4309 // Homogeneous aggregates passed in registers will have their elements split
4310 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4311 // qN+1, ...). We reload and store into a temporary local variable
4312 // contiguously.
4313 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4314 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4315 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4316 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4317
4318 for (unsigned i = 0; i < NumMembers; ++i) {
4319 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4320 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4321 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4322 llvm::PointerType::getUnqual(BaseTy));
4323 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4324
4325 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4326 CGF.Builder.CreateStore(Elem, StoreAddr);
4327 }
4328
4329 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4330 } else {
4331 // Otherwise the object is contiguous in memory
4332 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4333 }
4334
4335 CGF.EmitBranch(ContBlock);
4336
4337 //=======================================
4338 // Argument was on the stack
4339 //=======================================
4340 CGF.EmitBlock(OnStackBlock);
4341
4342 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4343 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4344 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4345
4346 // Again, stack arguments may need realigmnent. In this case both integer and
4347 // floating-point ones might be affected.
4348 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4349 int Align = getContext().getTypeAlign(Ty) / 8;
4350
4351 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4352
4353 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4354 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4355 "align_stack");
4356 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4357 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4358 "align_stack");
4359
4360 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4361 }
4362
4363 uint64_t StackSize;
4364 if (AI.isDirect())
4365 StackSize = getContext().getTypeSize(Ty) / 8;
4366 else
4367 StackSize = 8;
4368
4369 // All stack slots are 8 bytes
4370 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4371
4372 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4373 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4374 "new_stack");
4375
4376 // Write the new value of __stack for the next call to va_arg
4377 CGF.Builder.CreateStore(NewStack, stack_p);
4378
4379 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4380
4381 CGF.EmitBranch(ContBlock);
4382
4383 //=======================================
4384 // Tidy up
4385 //=======================================
4386 CGF.EmitBlock(ContBlock);
4387
4388 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4389 ResAddr->addIncoming(RegAddr, InRegBlock);
4390 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4391
4392 if (AI.isDirect())
4393 return ResAddr;
4394
4395 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4396}
4397
4398//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004399// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004400//===----------------------------------------------------------------------===//
4401
4402namespace {
4403
Justin Holewinski83e96682012-05-24 17:43:12 +00004404class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004405public:
Justin Holewinski36837432013-03-30 14:38:24 +00004406 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004407
4408 ABIArgInfo classifyReturnType(QualType RetTy) const;
4409 ABIArgInfo classifyArgumentType(QualType Ty) const;
4410
4411 virtual void computeInfo(CGFunctionInfo &FI) const;
4412 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4413 CodeGenFunction &CFG) const;
4414};
4415
Justin Holewinski83e96682012-05-24 17:43:12 +00004416class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004417public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004418 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4419 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski38031972011-10-05 17:58:44 +00004420
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004421 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4422 CodeGen::CodeGenModule &M) const;
Justin Holewinski36837432013-03-30 14:38:24 +00004423private:
4424 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004425};
4426
Justin Holewinski83e96682012-05-24 17:43:12 +00004427ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004428 if (RetTy->isVoidType())
4429 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004430
4431 // note: this is different from default ABI
4432 if (!RetTy->isScalarType())
4433 return ABIArgInfo::getDirect();
4434
4435 // Treat an enum type as its underlying type.
4436 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4437 RetTy = EnumTy->getDecl()->getIntegerType();
4438
4439 return (RetTy->isPromotableIntegerType() ?
4440 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004441}
4442
Justin Holewinski83e96682012-05-24 17:43:12 +00004443ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004444 // Treat an enum type as its underlying type.
4445 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4446 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004447
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004448 return (Ty->isPromotableIntegerType() ?
4449 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004450}
4451
Justin Holewinski83e96682012-05-24 17:43:12 +00004452void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4454 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4455 it != ie; ++it)
4456 it->info = classifyArgumentType(it->type);
4457
4458 // Always honor user-specified calling convention.
4459 if (FI.getCallingConvention() != llvm::CallingConv::C)
4460 return;
4461
John McCall882987f2013-02-28 19:01:20 +00004462 FI.setEffectiveCallingConvention(getRuntimeCC());
4463}
4464
Justin Holewinski83e96682012-05-24 17:43:12 +00004465llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4466 CodeGenFunction &CFG) const {
4467 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004468}
4469
Justin Holewinski83e96682012-05-24 17:43:12 +00004470void NVPTXTargetCodeGenInfo::
4471SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4472 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004473 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4474 if (!FD) return;
4475
4476 llvm::Function *F = cast<llvm::Function>(GV);
4477
4478 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004479 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004480 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004481 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004482 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004483 // OpenCL __kernel functions get kernel metadata
4484 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004485 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004486 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004487 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004488 }
Justin Holewinski38031972011-10-05 17:58:44 +00004489
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004490 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004491 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004492 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004493 // __global__ functions cannot be called from the device, we do not
4494 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004495 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004496 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004497 }
4498}
4499
Justin Holewinski36837432013-03-30 14:38:24 +00004500void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4501 llvm::Module *M = F->getParent();
4502 llvm::LLVMContext &Ctx = M->getContext();
4503
4504 // Get "nvvm.annotations" metadata node
4505 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4506
4507 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4508 llvm::SmallVector<llvm::Value *, 3> MDVals;
4509 MDVals.push_back(F);
4510 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4511 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4512
4513 // Append metadata to nvvm.annotations
4514 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4515}
4516
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004517}
4518
4519//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004520// SystemZ ABI Implementation
4521//===----------------------------------------------------------------------===//
4522
4523namespace {
4524
4525class SystemZABIInfo : public ABIInfo {
4526public:
4527 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4528
4529 bool isPromotableIntegerType(QualType Ty) const;
4530 bool isCompoundType(QualType Ty) const;
4531 bool isFPArgumentType(QualType Ty) const;
4532
4533 ABIArgInfo classifyReturnType(QualType RetTy) const;
4534 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4535
4536 virtual void computeInfo(CGFunctionInfo &FI) const {
4537 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4538 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4539 it != ie; ++it)
4540 it->info = classifyArgumentType(it->type);
4541 }
4542
4543 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4544 CodeGenFunction &CGF) const;
4545};
4546
4547class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4548public:
4549 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4550 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4551};
4552
4553}
4554
4555bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4556 // Treat an enum type as its underlying type.
4557 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4558 Ty = EnumTy->getDecl()->getIntegerType();
4559
4560 // Promotable integer types are required to be promoted by the ABI.
4561 if (Ty->isPromotableIntegerType())
4562 return true;
4563
4564 // 32-bit values must also be promoted.
4565 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4566 switch (BT->getKind()) {
4567 case BuiltinType::Int:
4568 case BuiltinType::UInt:
4569 return true;
4570 default:
4571 return false;
4572 }
4573 return false;
4574}
4575
4576bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4577 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4578}
4579
4580bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4581 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4582 switch (BT->getKind()) {
4583 case BuiltinType::Float:
4584 case BuiltinType::Double:
4585 return true;
4586 default:
4587 return false;
4588 }
4589
4590 if (const RecordType *RT = Ty->getAsStructureType()) {
4591 const RecordDecl *RD = RT->getDecl();
4592 bool Found = false;
4593
4594 // If this is a C++ record, check the bases first.
4595 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4596 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4597 E = CXXRD->bases_end(); I != E; ++I) {
4598 QualType Base = I->getType();
4599
4600 // Empty bases don't affect things either way.
4601 if (isEmptyRecord(getContext(), Base, true))
4602 continue;
4603
4604 if (Found)
4605 return false;
4606 Found = isFPArgumentType(Base);
4607 if (!Found)
4608 return false;
4609 }
4610
4611 // Check the fields.
4612 for (RecordDecl::field_iterator I = RD->field_begin(),
4613 E = RD->field_end(); I != E; ++I) {
4614 const FieldDecl *FD = *I;
4615
4616 // Empty bitfields don't affect things either way.
4617 // Unlike isSingleElementStruct(), empty structure and array fields
4618 // do count. So do anonymous bitfields that aren't zero-sized.
4619 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4620 return true;
4621
4622 // Unlike isSingleElementStruct(), arrays do not count.
4623 // Nested isFPArgumentType structures still do though.
4624 if (Found)
4625 return false;
4626 Found = isFPArgumentType(FD->getType());
4627 if (!Found)
4628 return false;
4629 }
4630
4631 // Unlike isSingleElementStruct(), trailing padding is allowed.
4632 // An 8-byte aligned struct s { float f; } is passed as a double.
4633 return Found;
4634 }
4635
4636 return false;
4637}
4638
4639llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4640 CodeGenFunction &CGF) const {
4641 // Assume that va_list type is correct; should be pointer to LLVM type:
4642 // struct {
4643 // i64 __gpr;
4644 // i64 __fpr;
4645 // i8 *__overflow_arg_area;
4646 // i8 *__reg_save_area;
4647 // };
4648
4649 // Every argument occupies 8 bytes and is passed by preference in either
4650 // GPRs or FPRs.
4651 Ty = CGF.getContext().getCanonicalType(Ty);
4652 ABIArgInfo AI = classifyArgumentType(Ty);
4653 bool InFPRs = isFPArgumentType(Ty);
4654
4655 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4656 bool IsIndirect = AI.isIndirect();
4657 unsigned UnpaddedBitSize;
4658 if (IsIndirect) {
4659 APTy = llvm::PointerType::getUnqual(APTy);
4660 UnpaddedBitSize = 64;
4661 } else
4662 UnpaddedBitSize = getContext().getTypeSize(Ty);
4663 unsigned PaddedBitSize = 64;
4664 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4665
4666 unsigned PaddedSize = PaddedBitSize / 8;
4667 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4668
4669 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4670 if (InFPRs) {
4671 MaxRegs = 4; // Maximum of 4 FPR arguments
4672 RegCountField = 1; // __fpr
4673 RegSaveIndex = 16; // save offset for f0
4674 RegPadding = 0; // floats are passed in the high bits of an FPR
4675 } else {
4676 MaxRegs = 5; // Maximum of 5 GPR arguments
4677 RegCountField = 0; // __gpr
4678 RegSaveIndex = 2; // save offset for r2
4679 RegPadding = Padding; // values are passed in the low bits of a GPR
4680 }
4681
4682 llvm::Value *RegCountPtr =
4683 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4684 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4685 llvm::Type *IndexTy = RegCount->getType();
4686 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4687 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00004688 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00004689
4690 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4691 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4692 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4693 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4694
4695 // Emit code to load the value if it was passed in registers.
4696 CGF.EmitBlock(InRegBlock);
4697
4698 // Work out the address of an argument register.
4699 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4700 llvm::Value *ScaledRegCount =
4701 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4702 llvm::Value *RegBase =
4703 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4704 llvm::Value *RegOffset =
4705 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4706 llvm::Value *RegSaveAreaPtr =
4707 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4708 llvm::Value *RegSaveArea =
4709 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4710 llvm::Value *RawRegAddr =
4711 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4712 llvm::Value *RegAddr =
4713 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4714
4715 // Update the register count
4716 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4717 llvm::Value *NewRegCount =
4718 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4719 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4720 CGF.EmitBranch(ContBlock);
4721
4722 // Emit code to load the value if it was passed in memory.
4723 CGF.EmitBlock(InMemBlock);
4724
4725 // Work out the address of a stack argument.
4726 llvm::Value *OverflowArgAreaPtr =
4727 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4728 llvm::Value *OverflowArgArea =
4729 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4730 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4731 llvm::Value *RawMemAddr =
4732 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4733 llvm::Value *MemAddr =
4734 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4735
4736 // Update overflow_arg_area_ptr pointer
4737 llvm::Value *NewOverflowArgArea =
4738 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4739 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4740 CGF.EmitBranch(ContBlock);
4741
4742 // Return the appropriate result.
4743 CGF.EmitBlock(ContBlock);
4744 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4745 ResAddr->addIncoming(RegAddr, InRegBlock);
4746 ResAddr->addIncoming(MemAddr, InMemBlock);
4747
4748 if (IsIndirect)
4749 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4750
4751 return ResAddr;
4752}
4753
John McCall1fe2a8c2013-06-18 02:46:29 +00004754bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4755 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4756 assert(Triple.getArch() == llvm::Triple::x86);
4757
4758 switch (Opts.getStructReturnConvention()) {
4759 case CodeGenOptions::SRCK_Default:
4760 break;
4761 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4762 return false;
4763 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4764 return true;
4765 }
4766
4767 if (Triple.isOSDarwin())
4768 return true;
4769
4770 switch (Triple.getOS()) {
4771 case llvm::Triple::Cygwin:
4772 case llvm::Triple::MinGW32:
4773 case llvm::Triple::AuroraUX:
4774 case llvm::Triple::DragonFly:
4775 case llvm::Triple::FreeBSD:
4776 case llvm::Triple::OpenBSD:
4777 case llvm::Triple::Bitrig:
4778 case llvm::Triple::Win32:
4779 return true;
4780 default:
4781 return false;
4782 }
4783}
Ulrich Weigand47445072013-05-06 16:26:41 +00004784
4785ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4786 if (RetTy->isVoidType())
4787 return ABIArgInfo::getIgnore();
4788 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4789 return ABIArgInfo::getIndirect(0);
4790 return (isPromotableIntegerType(RetTy) ?
4791 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4792}
4793
4794ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4795 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004796 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004797 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4798
4799 // Integers and enums are extended to full register width.
4800 if (isPromotableIntegerType(Ty))
4801 return ABIArgInfo::getExtend();
4802
4803 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4804 uint64_t Size = getContext().getTypeSize(Ty);
4805 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004806 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004807
4808 // Handle small structures.
4809 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4810 // Structures with flexible arrays have variable length, so really
4811 // fail the size test above.
4812 const RecordDecl *RD = RT->getDecl();
4813 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004814 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004815
4816 // The structure is passed as an unextended integer, a float, or a double.
4817 llvm::Type *PassTy;
4818 if (isFPArgumentType(Ty)) {
4819 assert(Size == 32 || Size == 64);
4820 if (Size == 32)
4821 PassTy = llvm::Type::getFloatTy(getVMContext());
4822 else
4823 PassTy = llvm::Type::getDoubleTy(getVMContext());
4824 } else
4825 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4826 return ABIArgInfo::getDirect(PassTy);
4827 }
4828
4829 // Non-structure compounds are passed indirectly.
4830 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004831 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004832
4833 return ABIArgInfo::getDirect(0);
4834}
4835
4836//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004837// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004838//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004839
4840namespace {
4841
4842class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4843public:
Chris Lattner2b037972010-07-29 02:01:43 +00004844 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4845 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004846 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4847 CodeGen::CodeGenModule &M) const;
4848};
4849
4850}
4851
4852void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4853 llvm::GlobalValue *GV,
4854 CodeGen::CodeGenModule &M) const {
4855 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4856 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4857 // Handle 'interrupt' attribute:
4858 llvm::Function *F = cast<llvm::Function>(GV);
4859
4860 // Step 1: Set ISR calling convention.
4861 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4862
4863 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004864 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004865
4866 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004867 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004868 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004869 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004870 GV, &M.getModule());
4871 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004872 }
4873}
4874
Chris Lattner0cf24192010-06-28 20:05:43 +00004875//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004876// MIPS ABI Implementation. This works for both little-endian and
4877// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004878//===----------------------------------------------------------------------===//
4879
John McCall943fae92010-05-27 06:19:26 +00004880namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004881class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004882 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004883 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4884 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004885 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004886 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004887 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004888 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004889public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004890 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004891 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004892 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004893
4894 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004895 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004896 virtual void computeInfo(CGFunctionInfo &FI) const;
4897 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4898 CodeGenFunction &CGF) const;
4899};
4900
John McCall943fae92010-05-27 06:19:26 +00004901class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004902 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004903public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004904 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4905 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004906 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004907
4908 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4909 return 29;
4910 }
4911
Reed Kotler373feca2013-01-16 17:10:28 +00004912 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4913 CodeGen::CodeGenModule &CGM) const {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004914 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4915 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004916 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004917 if (FD->hasAttr<Mips16Attr>()) {
4918 Fn->addFnAttr("mips16");
4919 }
4920 else if (FD->hasAttr<NoMips16Attr>()) {
4921 Fn->addFnAttr("nomips16");
4922 }
Reed Kotler373feca2013-01-16 17:10:28 +00004923 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004924
John McCall943fae92010-05-27 06:19:26 +00004925 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004926 llvm::Value *Address) const;
John McCall3480ef22011-08-30 01:42:09 +00004927
4928 unsigned getSizeOfUnwindException() const {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004929 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004930 }
John McCall943fae92010-05-27 06:19:26 +00004931};
4932}
4933
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004934void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004935 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004936 llvm::IntegerType *IntTy =
4937 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004938
4939 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4940 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4941 ArgList.push_back(IntTy);
4942
4943 // If necessary, add one more integer type to ArgList.
4944 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4945
4946 if (R)
4947 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004948}
4949
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004950// In N32/64, an aligned double precision floating point field is passed in
4951// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004952llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004953 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4954
4955 if (IsO32) {
4956 CoerceToIntArgs(TySize, ArgList);
4957 return llvm::StructType::get(getVMContext(), ArgList);
4958 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004959
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004960 if (Ty->isComplexType())
4961 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004962
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004963 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004964
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004965 // Unions/vectors are passed in integer registers.
4966 if (!RT || !RT->isStructureOrClassType()) {
4967 CoerceToIntArgs(TySize, ArgList);
4968 return llvm::StructType::get(getVMContext(), ArgList);
4969 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004970
4971 const RecordDecl *RD = RT->getDecl();
4972 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004973 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004974
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004975 uint64_t LastOffset = 0;
4976 unsigned idx = 0;
4977 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4978
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004979 // Iterate over fields in the struct/class and check if there are any aligned
4980 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004981 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4982 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004983 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004984 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4985
4986 if (!BT || BT->getKind() != BuiltinType::Double)
4987 continue;
4988
4989 uint64_t Offset = Layout.getFieldOffset(idx);
4990 if (Offset % 64) // Ignore doubles that are not aligned.
4991 continue;
4992
4993 // Add ((Offset - LastOffset) / 64) args of type i64.
4994 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4995 ArgList.push_back(I64);
4996
4997 // Add double type.
4998 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4999 LastOffset = Offset + 64;
5000 }
5001
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005002 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5003 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005004
5005 return llvm::StructType::get(getVMContext(), ArgList);
5006}
5007
Akira Hatanakaddd66342013-10-29 18:41:15 +00005008llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5009 uint64_t Offset) const {
5010 if (OrigOffset + MinABIStackAlignInBytes > Offset)
5011 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005012
Akira Hatanakaddd66342013-10-29 18:41:15 +00005013 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005014}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005015
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005016ABIArgInfo
5017MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005018 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005019 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005020 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005021
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005022 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5023 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005024 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5025 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005026
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005027 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005028 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005029 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005030 return ABIArgInfo::getIgnore();
5031
Mark Lacey3825e832013-10-06 01:33:34 +00005032 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005033 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005034 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005035 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005036
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005037 // If we have reached here, aggregates are passed directly by coercing to
5038 // another structure type. Padding is inserted if the offset of the
5039 // aggregate is unaligned.
5040 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005041 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005042 }
5043
5044 // Treat an enum type as its underlying type.
5045 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5046 Ty = EnumTy->getDecl()->getIntegerType();
5047
Akira Hatanaka1632af62012-01-09 19:31:25 +00005048 if (Ty->isPromotableIntegerType())
5049 return ABIArgInfo::getExtend();
5050
Akira Hatanakaddd66342013-10-29 18:41:15 +00005051 return ABIArgInfo::getDirect(
5052 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005053}
5054
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005055llvm::Type*
5056MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005057 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005058 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005059
Akira Hatanakab6f74432012-02-09 18:49:26 +00005060 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005061 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005062 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5063 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005064
Akira Hatanakab6f74432012-02-09 18:49:26 +00005065 // N32/64 returns struct/classes in floating point registers if the
5066 // following conditions are met:
5067 // 1. The size of the struct/class is no larger than 128-bit.
5068 // 2. The struct/class has one or two fields all of which are floating
5069 // point types.
5070 // 3. The offset of the first field is zero (this follows what gcc does).
5071 //
5072 // Any other composite results are returned in integer registers.
5073 //
5074 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5075 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5076 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005077 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005078
Akira Hatanakab6f74432012-02-09 18:49:26 +00005079 if (!BT || !BT->isFloatingPoint())
5080 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005081
David Blaikie2d7c57e2012-04-30 02:36:29 +00005082 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005083 }
5084
5085 if (b == e)
5086 return llvm::StructType::get(getVMContext(), RTList,
5087 RD->hasAttr<PackedAttr>());
5088
5089 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005090 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005091 }
5092
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005093 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005094 return llvm::StructType::get(getVMContext(), RTList);
5095}
5096
Akira Hatanakab579fe52011-06-02 00:09:17 +00005097ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005098 uint64_t Size = getContext().getTypeSize(RetTy);
5099
5100 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005101 return ABIArgInfo::getIgnore();
5102
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005103 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00005104 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005105 return ABIArgInfo::getIndirect(0);
5106
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005107 if (Size <= 128) {
5108 if (RetTy->isAnyComplexType())
5109 return ABIArgInfo::getDirect();
5110
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005111 // O32 returns integer vectors in registers.
5112 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
5113 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5114
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005115 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005116 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5117 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005118
5119 return ABIArgInfo::getIndirect(0);
5120 }
5121
5122 // Treat an enum type as its underlying type.
5123 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5124 RetTy = EnumTy->getDecl()->getIntegerType();
5125
5126 return (RetTy->isPromotableIntegerType() ?
5127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5128}
5129
5130void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005131 ABIArgInfo &RetInfo = FI.getReturnInfo();
5132 RetInfo = classifyReturnType(FI.getReturnType());
5133
5134 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005135 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005136
Akira Hatanakab579fe52011-06-02 00:09:17 +00005137 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5138 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005139 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005140}
5141
5142llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5143 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005144 llvm::Type *BP = CGF.Int8PtrTy;
5145 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005146
5147 CGBuilderTy &Builder = CGF.Builder;
5148 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5149 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00005150 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005151 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5152 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00005153 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00005154 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005155
5156 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00005157 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5158 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5159 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5160 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005161 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5162 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5163 }
5164 else
5165 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5166
5167 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00005168 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005169 uint64_t Offset =
5170 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5171 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00005172 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005173 "ap.next");
5174 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5175
5176 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005177}
5178
John McCall943fae92010-05-27 06:19:26 +00005179bool
5180MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5181 llvm::Value *Address) const {
5182 // This information comes from gcc's implementation, which seems to
5183 // as canonical as it gets.
5184
John McCall943fae92010-05-27 06:19:26 +00005185 // Everything on MIPS is 4 bytes. Double-precision FP registers
5186 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005187 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005188
5189 // 0-31 are the general purpose registers, $0 - $31.
5190 // 32-63 are the floating-point registers, $f0 - $f31.
5191 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5192 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005193 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005194
5195 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5196 // They are one bit wide and ignored here.
5197
5198 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5199 // (coprocessor 1 is the FP unit)
5200 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5201 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5202 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005203 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005204 return false;
5205}
5206
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005207//===----------------------------------------------------------------------===//
5208// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5209// Currently subclassed only to implement custom OpenCL C function attribute
5210// handling.
5211//===----------------------------------------------------------------------===//
5212
5213namespace {
5214
5215class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5216public:
5217 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5218 : DefaultTargetCodeGenInfo(CGT) {}
5219
5220 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5221 CodeGen::CodeGenModule &M) const;
5222};
5223
5224void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5225 llvm::GlobalValue *GV,
5226 CodeGen::CodeGenModule &M) const {
5227 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5228 if (!FD) return;
5229
5230 llvm::Function *F = cast<llvm::Function>(GV);
5231
David Blaikiebbafb8a2012-03-11 07:00:24 +00005232 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005233 if (FD->hasAttr<OpenCLKernelAttr>()) {
5234 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005235 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005236 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5237 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005238 // Convert the reqd_work_group_size() attributes to metadata.
5239 llvm::LLVMContext &Context = F->getContext();
5240 llvm::NamedMDNode *OpenCLMetadata =
5241 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5242
5243 SmallVector<llvm::Value*, 5> Operands;
5244 Operands.push_back(F);
5245
Chris Lattnerece04092012-02-07 00:39:47 +00005246 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005247 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005248 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005249 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005250 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005251 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005252
5253 // Add a boolean constant operand for "required" (true) or "hint" (false)
5254 // for implementing the work_group_size_hint attr later. Currently
5255 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005256 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005257 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5258 }
5259 }
5260 }
5261}
5262
5263}
John McCall943fae92010-05-27 06:19:26 +00005264
Tony Linthicum76329bf2011-12-12 21:14:55 +00005265//===----------------------------------------------------------------------===//
5266// Hexagon ABI Implementation
5267//===----------------------------------------------------------------------===//
5268
5269namespace {
5270
5271class HexagonABIInfo : public ABIInfo {
5272
5273
5274public:
5275 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5276
5277private:
5278
5279 ABIArgInfo classifyReturnType(QualType RetTy) const;
5280 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5281
5282 virtual void computeInfo(CGFunctionInfo &FI) const;
5283
5284 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5285 CodeGenFunction &CGF) const;
5286};
5287
5288class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5289public:
5290 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5291 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5292
5293 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5294 return 29;
5295 }
5296};
5297
5298}
5299
5300void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5301 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5302 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5303 it != ie; ++it)
5304 it->info = classifyArgumentType(it->type);
5305}
5306
5307ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5308 if (!isAggregateTypeForABI(Ty)) {
5309 // Treat an enum type as its underlying type.
5310 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5311 Ty = EnumTy->getDecl()->getIntegerType();
5312
5313 return (Ty->isPromotableIntegerType() ?
5314 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5315 }
5316
5317 // Ignore empty records.
5318 if (isEmptyRecord(getContext(), Ty, true))
5319 return ABIArgInfo::getIgnore();
5320
Mark Lacey3825e832013-10-06 01:33:34 +00005321 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005322 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005323
5324 uint64_t Size = getContext().getTypeSize(Ty);
5325 if (Size > 64)
5326 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5327 // Pass in the smallest viable integer type.
5328 else if (Size > 32)
5329 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5330 else if (Size > 16)
5331 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5332 else if (Size > 8)
5333 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5334 else
5335 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5336}
5337
5338ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5339 if (RetTy->isVoidType())
5340 return ABIArgInfo::getIgnore();
5341
5342 // Large vector types should be returned via memory.
5343 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5344 return ABIArgInfo::getIndirect(0);
5345
5346 if (!isAggregateTypeForABI(RetTy)) {
5347 // Treat an enum type as its underlying type.
5348 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5349 RetTy = EnumTy->getDecl()->getIntegerType();
5350
5351 return (RetTy->isPromotableIntegerType() ?
5352 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5353 }
5354
5355 // Structures with either a non-trivial destructor or a non-trivial
5356 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005357 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005358 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5359
5360 if (isEmptyRecord(getContext(), RetTy, true))
5361 return ABIArgInfo::getIgnore();
5362
5363 // Aggregates <= 8 bytes are returned in r0; other aggregates
5364 // are returned indirectly.
5365 uint64_t Size = getContext().getTypeSize(RetTy);
5366 if (Size <= 64) {
5367 // Return in the smallest viable integer type.
5368 if (Size <= 8)
5369 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5370 if (Size <= 16)
5371 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5372 if (Size <= 32)
5373 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5374 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5375 }
5376
5377 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5378}
5379
5380llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005381 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005382 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005383 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005384
5385 CGBuilderTy &Builder = CGF.Builder;
5386 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5387 "ap");
5388 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5389 llvm::Type *PTy =
5390 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5391 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5392
5393 uint64_t Offset =
5394 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5395 llvm::Value *NextAddr =
5396 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5397 "ap.next");
5398 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5399
5400 return AddrTyped;
5401}
5402
5403
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005404//===----------------------------------------------------------------------===//
5405// SPARC v9 ABI Implementation.
5406// Based on the SPARC Compliance Definition version 2.4.1.
5407//
5408// Function arguments a mapped to a nominal "parameter array" and promoted to
5409// registers depending on their type. Each argument occupies 8 or 16 bytes in
5410// the array, structs larger than 16 bytes are passed indirectly.
5411//
5412// One case requires special care:
5413//
5414// struct mixed {
5415// int i;
5416// float f;
5417// };
5418//
5419// When a struct mixed is passed by value, it only occupies 8 bytes in the
5420// parameter array, but the int is passed in an integer register, and the float
5421// is passed in a floating point register. This is represented as two arguments
5422// with the LLVM IR inreg attribute:
5423//
5424// declare void f(i32 inreg %i, float inreg %f)
5425//
5426// The code generator will only allocate 4 bytes from the parameter array for
5427// the inreg arguments. All other arguments are allocated a multiple of 8
5428// bytes.
5429//
5430namespace {
5431class SparcV9ABIInfo : public ABIInfo {
5432public:
5433 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5434
5435private:
5436 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5437 virtual void computeInfo(CGFunctionInfo &FI) const;
5438 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5439 CodeGenFunction &CGF) const;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005440
5441 // Coercion type builder for structs passed in registers. The coercion type
5442 // serves two purposes:
5443 //
5444 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5445 // in registers.
5446 // 2. Expose aligned floating point elements as first-level elements, so the
5447 // code generator knows to pass them in floating point registers.
5448 //
5449 // We also compute the InReg flag which indicates that the struct contains
5450 // aligned 32-bit floats.
5451 //
5452 struct CoerceBuilder {
5453 llvm::LLVMContext &Context;
5454 const llvm::DataLayout &DL;
5455 SmallVector<llvm::Type*, 8> Elems;
5456 uint64_t Size;
5457 bool InReg;
5458
5459 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5460 : Context(c), DL(dl), Size(0), InReg(false) {}
5461
5462 // Pad Elems with integers until Size is ToSize.
5463 void pad(uint64_t ToSize) {
5464 assert(ToSize >= Size && "Cannot remove elements");
5465 if (ToSize == Size)
5466 return;
5467
5468 // Finish the current 64-bit word.
5469 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5470 if (Aligned > Size && Aligned <= ToSize) {
5471 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5472 Size = Aligned;
5473 }
5474
5475 // Add whole 64-bit words.
5476 while (Size + 64 <= ToSize) {
5477 Elems.push_back(llvm::Type::getInt64Ty(Context));
5478 Size += 64;
5479 }
5480
5481 // Final in-word padding.
5482 if (Size < ToSize) {
5483 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5484 Size = ToSize;
5485 }
5486 }
5487
5488 // Add a floating point element at Offset.
5489 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5490 // Unaligned floats are treated as integers.
5491 if (Offset % Bits)
5492 return;
5493 // The InReg flag is only required if there are any floats < 64 bits.
5494 if (Bits < 64)
5495 InReg = true;
5496 pad(Offset);
5497 Elems.push_back(Ty);
5498 Size = Offset + Bits;
5499 }
5500
5501 // Add a struct type to the coercion type, starting at Offset (in bits).
5502 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5503 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5504 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5505 llvm::Type *ElemTy = StrTy->getElementType(i);
5506 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5507 switch (ElemTy->getTypeID()) {
5508 case llvm::Type::StructTyID:
5509 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5510 break;
5511 case llvm::Type::FloatTyID:
5512 addFloat(ElemOffset, ElemTy, 32);
5513 break;
5514 case llvm::Type::DoubleTyID:
5515 addFloat(ElemOffset, ElemTy, 64);
5516 break;
5517 case llvm::Type::FP128TyID:
5518 addFloat(ElemOffset, ElemTy, 128);
5519 break;
5520 case llvm::Type::PointerTyID:
5521 if (ElemOffset % 64 == 0) {
5522 pad(ElemOffset);
5523 Elems.push_back(ElemTy);
5524 Size += 64;
5525 }
5526 break;
5527 default:
5528 break;
5529 }
5530 }
5531 }
5532
5533 // Check if Ty is a usable substitute for the coercion type.
5534 bool isUsableType(llvm::StructType *Ty) const {
5535 if (Ty->getNumElements() != Elems.size())
5536 return false;
5537 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5538 if (Elems[i] != Ty->getElementType(i))
5539 return false;
5540 return true;
5541 }
5542
5543 // Get the coercion type as a literal struct type.
5544 llvm::Type *getType() const {
5545 if (Elems.size() == 1)
5546 return Elems.front();
5547 else
5548 return llvm::StructType::get(Context, Elems);
5549 }
5550 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005551};
5552} // end anonymous namespace
5553
5554ABIArgInfo
5555SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5556 if (Ty->isVoidType())
5557 return ABIArgInfo::getIgnore();
5558
5559 uint64_t Size = getContext().getTypeSize(Ty);
5560
5561 // Anything too big to fit in registers is passed with an explicit indirect
5562 // pointer / sret pointer.
5563 if (Size > SizeLimit)
5564 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5565
5566 // Treat an enum type as its underlying type.
5567 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5568 Ty = EnumTy->getDecl()->getIntegerType();
5569
5570 // Integer types smaller than a register are extended.
5571 if (Size < 64 && Ty->isIntegerType())
5572 return ABIArgInfo::getExtend();
5573
5574 // Other non-aggregates go in registers.
5575 if (!isAggregateTypeForABI(Ty))
5576 return ABIArgInfo::getDirect();
5577
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005578 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5579 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5580 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5581 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5582
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005583 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005584 // Build a coercion type from the LLVM struct type.
5585 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5586 if (!StrTy)
5587 return ABIArgInfo::getDirect();
5588
5589 CoerceBuilder CB(getVMContext(), getDataLayout());
5590 CB.addStruct(0, StrTy);
5591 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5592
5593 // Try to use the original type for coercion.
5594 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5595
5596 if (CB.InReg)
5597 return ABIArgInfo::getDirectInReg(CoerceTy);
5598 else
5599 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005600}
5601
5602llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5603 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005604 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5605 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5606 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5607 AI.setCoerceToType(ArgTy);
5608
5609 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5610 CGBuilderTy &Builder = CGF.Builder;
5611 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5612 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5613 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5614 llvm::Value *ArgAddr;
5615 unsigned Stride;
5616
5617 switch (AI.getKind()) {
5618 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005619 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005620 llvm_unreachable("Unsupported ABI kind for va_arg");
5621
5622 case ABIArgInfo::Extend:
5623 Stride = 8;
5624 ArgAddr = Builder
5625 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5626 "extend");
5627 break;
5628
5629 case ABIArgInfo::Direct:
5630 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5631 ArgAddr = Addr;
5632 break;
5633
5634 case ABIArgInfo::Indirect:
5635 Stride = 8;
5636 ArgAddr = Builder.CreateBitCast(Addr,
5637 llvm::PointerType::getUnqual(ArgPtrTy),
5638 "indirect");
5639 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5640 break;
5641
5642 case ABIArgInfo::Ignore:
5643 return llvm::UndefValue::get(ArgPtrTy);
5644 }
5645
5646 // Update VAList.
5647 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5648 Builder.CreateStore(Addr, VAListAddrAsBPP);
5649
5650 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005651}
5652
5653void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5654 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5655 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5656 it != ie; ++it)
5657 it->info = classifyType(it->type, 16 * 8);
5658}
5659
5660namespace {
5661class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5662public:
5663 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5664 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00005665
5666 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5667 return 14;
5668 }
5669
5670 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5671 llvm::Value *Address) const;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005672};
5673} // end anonymous namespace
5674
Roman Divackyf02c9942014-02-24 18:46:27 +00005675bool
5676SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5677 llvm::Value *Address) const {
5678 // This is calculated from the LLVM and GCC tables and verified
5679 // against gcc output. AFAIK all ABIs use the same encoding.
5680
5681 CodeGen::CGBuilderTy &Builder = CGF.Builder;
5682
5683 llvm::IntegerType *i8 = CGF.Int8Ty;
5684 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
5685 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
5686
5687 // 0-31: the 8-byte general-purpose registers
5688 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
5689
5690 // 32-63: f0-31, the 4-byte floating-point registers
5691 AssignToArrayRange(Builder, Address, Four8, 32, 63);
5692
5693 // Y = 64
5694 // PSR = 65
5695 // WIM = 66
5696 // TBR = 67
5697 // PC = 68
5698 // NPC = 69
5699 // FSR = 70
5700 // CSR = 71
5701 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
5702
5703 // 72-87: d0-15, the 8-byte floating-point registers
5704 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
5705
5706 return false;
5707}
5708
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005709
Robert Lytton0e076492013-08-13 09:43:10 +00005710//===----------------------------------------------------------------------===//
5711// Xcore ABI Implementation
5712//===----------------------------------------------------------------------===//
5713namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005714class XCoreABIInfo : public DefaultABIInfo {
5715public:
5716 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5717 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5718 CodeGenFunction &CGF) const;
5719};
5720
Robert Lytton0e076492013-08-13 09:43:10 +00005721class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5722public:
5723 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005724 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005725};
Robert Lytton2d196952013-10-11 10:29:34 +00005726} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005727
Robert Lytton7d1db152013-08-19 09:46:39 +00005728llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5729 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005730 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005731
Robert Lytton2d196952013-10-11 10:29:34 +00005732 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005733 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5734 CGF.Int8PtrPtrTy);
5735 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005736
Robert Lytton2d196952013-10-11 10:29:34 +00005737 // Handle the argument.
5738 ABIArgInfo AI = classifyArgumentType(Ty);
5739 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5740 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5741 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005742 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005743 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005744 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005745 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005746 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005747 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00005748 llvm_unreachable("Unsupported ABI kind for va_arg");
5749 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005750 Val = llvm::UndefValue::get(ArgPtrTy);
5751 ArgSize = 0;
5752 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005753 case ABIArgInfo::Extend:
5754 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005755 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5756 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5757 if (ArgSize < 4)
5758 ArgSize = 4;
5759 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005760 case ABIArgInfo::Indirect:
5761 llvm::Value *ArgAddr;
5762 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5763 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005764 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5765 ArgSize = 4;
5766 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005767 }
Robert Lytton2d196952013-10-11 10:29:34 +00005768
5769 // Increment the VAList.
5770 if (ArgSize) {
5771 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5772 Builder.CreateStore(APN, VAListAddrAsBPP);
5773 }
5774 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005775}
Robert Lytton0e076492013-08-13 09:43:10 +00005776
5777//===----------------------------------------------------------------------===//
5778// Driver code
5779//===----------------------------------------------------------------------===//
5780
Chris Lattner2b037972010-07-29 02:01:43 +00005781const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005782 if (TheTargetCodeGenInfo)
5783 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005784
John McCallc8e01702013-04-16 22:48:15 +00005785 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005786 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005787 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005788 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005789
Derek Schuff09338a22012-09-06 17:37:28 +00005790 case llvm::Triple::le32:
5791 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005792 case llvm::Triple::mips:
5793 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005794 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5795
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005796 case llvm::Triple::mips64:
5797 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005798 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5799
Tim Northover9bb857a2013-01-31 12:13:10 +00005800 case llvm::Triple::aarch64:
5801 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5802
Daniel Dunbard59655c2009-09-12 00:59:49 +00005803 case llvm::Triple::arm:
5804 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005805 {
5806 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005807 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005808 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005809 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005810 (CodeGenOpts.FloatABI != "soft" &&
5811 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005812 Kind = ARMABIInfo::AAPCS_VFP;
5813
Derek Schuffa2020962012-10-16 22:30:41 +00005814 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005815 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005816 return *(TheTargetCodeGenInfo =
5817 new NaClARMTargetCodeGenInfo(Types, Kind));
5818 default:
5819 return *(TheTargetCodeGenInfo =
5820 new ARMTargetCodeGenInfo(Types, Kind));
5821 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005822 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005823
John McCallea8d8bb2010-03-11 00:10:12 +00005824 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005825 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005826 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005827 if (Triple.isOSBinFormatELF())
5828 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5829 else
5830 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005831 case llvm::Triple::ppc64le:
5832 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5833 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005834
Peter Collingbournec947aae2012-05-20 23:28:41 +00005835 case llvm::Triple::nvptx:
5836 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005837 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005838
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005839 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005840 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005841
Ulrich Weigand47445072013-05-06 16:26:41 +00005842 case llvm::Triple::systemz:
5843 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5844
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005845 case llvm::Triple::tce:
5846 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5847
Eli Friedman33465822011-07-08 23:31:17 +00005848 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005849 bool IsDarwinVectorABI = Triple.isOSDarwin();
5850 bool IsSmallStructInRegABI =
5851 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5852 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005853
John McCall1fe2a8c2013-06-18 02:46:29 +00005854 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005855 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005856 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005857 IsDarwinVectorABI, IsSmallStructInRegABI,
5858 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005859 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005860 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005861 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005862 new X86_32TargetCodeGenInfo(Types,
5863 IsDarwinVectorABI, IsSmallStructInRegABI,
5864 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005865 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005866 }
Eli Friedman33465822011-07-08 23:31:17 +00005867 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005868
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005869 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005870 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005871
Chris Lattner04dc9572010-08-31 16:44:54 +00005872 switch (Triple.getOS()) {
5873 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005874 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005875 case llvm::Triple::Cygwin:
5876 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005877 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005878 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5879 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005880 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005881 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5882 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005883 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005884 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005885 case llvm::Triple::hexagon:
5886 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005887 case llvm::Triple::sparcv9:
5888 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005889 case llvm::Triple::xcore:
5890 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5891
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005892 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005893}