blob: 6e2c83e1fc429b2c66b3810e2168d320b793cf0f [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"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000023#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000026#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000027
28#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
40 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
41 Builder.CreateStore(Value, Cell);
42 }
43}
44
John McCalla1dee5302010-08-22 10:59:02 +000045static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000046 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000047 T->isMemberFunctionPointerType();
48}
49
Anton Korobeynikov244360d2009-06-05 22:08:42 +000050ABIInfo::~ABIInfo() {}
51
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000052static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000053 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 if (!RD)
56 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000057 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058}
59
60static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000061 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062 const RecordType *RT = T->getAs<RecordType>();
63 if (!RT)
64 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000065 return getRecordArgABI(RT, CXXABI);
66}
67
Reid Klecknerb1be6832014-11-15 01:41:41 +000068/// Pass transparent unions as if they were the type of the first element. Sema
69/// should ensure that all elements of the union have the same "machine type".
70static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
71 if (const RecordType *UT = Ty->getAsUnionType()) {
72 const RecordDecl *UD = UT->getDecl();
73 if (UD->hasAttr<TransparentUnionAttr>()) {
74 assert(!UD->field_empty() && "sema created an empty transparent union");
75 return UD->field_begin()->getType();
76 }
77 }
78 return Ty;
79}
80
Mark Lacey3825e832013-10-06 01:33:34 +000081CGCXXABI &ABIInfo::getCXXABI() const {
82 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000083}
84
Chris Lattner2b037972010-07-29 02:01:43 +000085ASTContext &ABIInfo::getContext() const {
86 return CGT.getContext();
87}
88
89llvm::LLVMContext &ABIInfo::getVMContext() const {
90 return CGT.getLLVMContext();
91}
92
Micah Villmowdd31ca12012-10-08 16:25:52 +000093const llvm::DataLayout &ABIInfo::getDataLayout() const {
94 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000095}
96
John McCallc8e01702013-04-16 22:48:15 +000097const TargetInfo &ABIInfo::getTarget() const {
98 return CGT.getTarget();
99}
Chris Lattner2b037972010-07-29 02:01:43 +0000100
Reid Klecknere9f6a712014-10-31 17:10:41 +0000101bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
102 return false;
103}
104
105bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
106 uint64_t Members) const {
107 return false;
108}
109
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000110void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000111 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000113 switch (TheKind) {
114 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000115 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000116 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000117 Ty->print(OS);
118 else
119 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000120 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000121 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000122 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000123 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000125 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000126 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000127 case InAlloca:
128 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
129 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000130 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000131 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000132 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000133 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000134 break;
135 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000136 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000137 break;
138 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000139 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000140}
141
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000142TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
143
John McCall3480ef22011-08-30 01:42:09 +0000144// If someone can figure out a general rule for this, that would be great.
145// It's probably just doomed to be platform-dependent, though.
146unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
147 // Verified for:
148 // x86-64 FreeBSD, Linux, Darwin
149 // x86-32 FreeBSD, Linux, Darwin
150 // PowerPC Linux, Darwin
151 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000152 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000153 return 32;
154}
155
John McCalla729c622012-02-17 03:33:10 +0000156bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
157 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000158 // The following conventions are known to require this to be false:
159 // x86_stdcall
160 // MIPS
161 // For everything else, we just prefer false unless we opt out.
162 return false;
163}
164
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000165void
166TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
167 llvm::SmallString<24> &Opt) const {
168 // This assumes the user is passing a library name like "rt" instead of a
169 // filename like "librt.a/so", and that they don't care whether it's static or
170 // dynamic.
171 Opt = "-l";
172 Opt += Lib;
173}
174
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000175static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000176
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000177/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000178/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000179static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
180 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000181 if (FD->isUnnamedBitfield())
182 return true;
183
184 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000185
Eli Friedman0b3f2012011-11-18 03:47:20 +0000186 // Constant arrays of empty records count as empty, strip them off.
187 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000188 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000189 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
190 if (AT->getSize() == 0)
191 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000192 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000193 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000194
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000195 const RecordType *RT = FT->getAs<RecordType>();
196 if (!RT)
197 return false;
198
199 // C++ record fields are never empty, at least in the Itanium ABI.
200 //
201 // FIXME: We should use a predicate for whether this behavior is true in the
202 // current ABI.
203 if (isa<CXXRecordDecl>(RT->getDecl()))
204 return false;
205
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000206 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000207}
208
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000209/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000210/// fields. Note that a structure with a flexible array member is not
211/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000212static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000213 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000214 if (!RT)
215 return 0;
216 const RecordDecl *RD = RT->getDecl();
217 if (RD->hasFlexibleArrayMember())
218 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000219
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000220 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000221 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000222 for (const auto &I : CXXRD->bases())
223 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000224 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000225
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000226 for (const auto *I : RD->fields())
227 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 return false;
229 return true;
230}
231
232/// isSingleElementStruct - Determine if a structure is a "single
233/// element struct", i.e. it has exactly one non-empty field or
234/// exactly one field which is itself a single element
235/// struct. Structures with flexible array members are never
236/// considered single element structs.
237///
238/// \return The field declaration for the single non-empty field, if
239/// it exists.
240static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
241 const RecordType *RT = T->getAsStructureType();
242 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000243 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000244
245 const RecordDecl *RD = RT->getDecl();
246 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000247 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000248
Craig Topper8a13c412014-05-21 05:09:00 +0000249 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000250
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000251 // If this is a C++ record, check the bases first.
252 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000253 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000254 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000255 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000256 continue;
257
258 // If we already found an element then this isn't a single-element struct.
259 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000260 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000261
262 // If this is non-empty and not a single element struct, the composite
263 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000264 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000265 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000266 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000267 }
268 }
269
270 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000271 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000272 QualType FT = FD->getType();
273
274 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000275 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000276 continue;
277
278 // If we already found an element then this isn't a single-element
279 // struct.
280 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000281 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000282
283 // Treat single element arrays as the element.
284 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
285 if (AT->getSize().getZExtValue() != 1)
286 break;
287 FT = AT->getElementType();
288 }
289
John McCalla1dee5302010-08-22 10:59:02 +0000290 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000291 Found = FT.getTypePtr();
292 } else {
293 Found = isSingleElementStruct(FT, Context);
294 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000295 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 }
297 }
298
Eli Friedmanee945342011-11-18 01:25:50 +0000299 // We don't consider a struct a single-element struct if it has
300 // padding beyond the element type.
301 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000302 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000303
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000304 return Found;
305}
306
307static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000308 // Treat complex types as the element type.
309 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
310 Ty = CTy->getElementType();
311
312 // Check for a type which we know has a simple scalar argument-passing
313 // convention without any padding. (We're specifically looking for 32
314 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000315 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000316 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000317 return false;
318
319 uint64_t Size = Context.getTypeSize(Ty);
320 return Size == 32 || Size == 64;
321}
322
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000323/// canExpandIndirectArgument - Test whether an argument type which is to be
324/// passed indirectly (on the stack) would have the equivalent layout if it was
325/// expanded into separate arguments. If so, we prefer to do the latter to avoid
326/// inhibiting optimizations.
327///
328// FIXME: This predicate is missing many cases, currently it just follows
329// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
330// should probably make this smarter, or better yet make the LLVM backend
331// capable of handling it.
332static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
333 // We can only expand structure types.
334 const RecordType *RT = Ty->getAs<RecordType>();
335 if (!RT)
336 return false;
337
338 // We can only expand (C) structures.
339 //
340 // FIXME: This needs to be generalized to handle classes as well.
341 const RecordDecl *RD = RT->getDecl();
342 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
343 return false;
344
Eli Friedmane5c85622011-11-18 01:32:26 +0000345 uint64_t Size = 0;
346
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000347 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000348 if (!is32Or64BitBasicType(FD->getType(), Context))
349 return false;
350
351 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
352 // how to expand them yet, and the predicate for telling if a bitfield still
353 // counts as "basic" is more complicated than what we were doing previously.
354 if (FD->isBitField())
355 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000356
357 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000358 }
359
Eli Friedmane5c85622011-11-18 01:32:26 +0000360 // Make sure there are not any holes in the struct.
361 if (Size != Context.getTypeSize(Ty))
362 return false;
363
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000364 return true;
365}
366
367namespace {
368/// DefaultABIInfo - The default implementation for ABI specific
369/// details. This implementation provides information which results in
370/// self-consistent and sensible LLVM IR generation, but does not
371/// conform to any particular ABI.
372class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000373public:
374 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000375
Chris Lattner458b2aa2010-07-29 02:16:43 +0000376 ABIArgInfo classifyReturnType(QualType RetTy) const;
377 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000378
Craig Topper4f12f102014-03-12 06:41:41 +0000379 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000380 if (!getCXXABI().classifyReturnType(FI))
381 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000382 for (auto &I : FI.arguments())
383 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384 }
385
Craig Topper4f12f102014-03-12 06:41:41 +0000386 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
387 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000388};
389
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000390class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
391public:
Chris Lattner2b037972010-07-29 02:01:43 +0000392 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
393 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000394};
395
396llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
397 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000398 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000399}
400
Chris Lattner458b2aa2010-07-29 02:16:43 +0000401ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000402 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000403 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000404
Chris Lattner9723d6c2010-03-11 18:19:55 +0000405 // Treat an enum type as its underlying type.
406 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
407 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000408
Chris Lattner9723d6c2010-03-11 18:19:55 +0000409 return (Ty->isPromotableIntegerType() ?
410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000411}
412
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000413ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
414 if (RetTy->isVoidType())
415 return ABIArgInfo::getIgnore();
416
417 if (isAggregateTypeForABI(RetTy))
418 return ABIArgInfo::getIndirect(0);
419
420 // Treat an enum type as its underlying type.
421 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
422 RetTy = EnumTy->getDecl()->getIntegerType();
423
424 return (RetTy->isPromotableIntegerType() ?
425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
426}
427
Derek Schuff09338a22012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000430//
431// This is a simplified version of the x86_32 ABI. Arguments and return values
432// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000433//===----------------------------------------------------------------------===//
434
435class PNaClABIInfo : public ABIInfo {
436 public:
437 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
438
439 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000440 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000441
Craig Topper4f12f102014-03-12 06:41:41 +0000442 void computeInfo(CGFunctionInfo &FI) const override;
443 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
444 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000445};
446
447class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
448 public:
449 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
450 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
451};
452
453void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000454 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456
Reid Kleckner40ca9132014-05-13 22:05:45 +0000457 for (auto &I : FI.arguments())
458 I.info = classifyArgumentType(I.type);
459}
Derek Schuff09338a22012-09-06 17:37:28 +0000460
461llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000463 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000464}
465
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000466/// \brief Classify argument of given type \p Ty.
467ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000468 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000469 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000470 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000471 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000472 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
473 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000474 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000475 } else if (Ty->isFloatingType()) {
476 // Floating-point types don't go inreg.
477 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000478 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000479
480 return (Ty->isPromotableIntegerType() ?
481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000482}
483
484ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
485 if (RetTy->isVoidType())
486 return ABIArgInfo::getIgnore();
487
Eli Benderskye20dad62013-04-04 22:49:35 +0000488 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000489 if (isAggregateTypeForABI(RetTy))
490 return ABIArgInfo::getIndirect(0);
491
492 // Treat an enum type as its underlying type.
493 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
494 RetTy = EnumTy->getDecl()->getIntegerType();
495
496 return (RetTy->isPromotableIntegerType() ?
497 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
498}
499
Chad Rosier651c1832013-03-25 21:00:27 +0000500/// IsX86_MMXType - Return true if this is an MMX type.
501bool IsX86_MMXType(llvm::Type *IRType) {
502 // 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 +0000503 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
504 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
505 IRType->getScalarSizeInBits() != 64;
506}
507
Jay Foad7c57be32011-07-11 09:56:20 +0000508static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000509 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000510 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000511 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
512 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
513 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000514 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000515 }
516
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000517 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000518 }
519
520 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000521 return Ty;
522}
523
Reid Kleckner80944df2014-10-31 22:00:51 +0000524/// Returns true if this type can be passed in SSE registers with the
525/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
526static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
527 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
528 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
529 return true;
530 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
531 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
532 // registers specially.
533 unsigned VecSize = Context.getTypeSize(VT);
534 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
535 return true;
536 }
537 return false;
538}
539
540/// Returns true if this aggregate is small enough to be passed in SSE registers
541/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
542static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
543 return NumMembers <= 4;
544}
545
Chris Lattner0cf24192010-06-28 20:05:43 +0000546//===----------------------------------------------------------------------===//
547// X86-32 ABI Implementation
548//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000549
Reid Kleckner661f35b2014-01-18 01:12:41 +0000550/// \brief Similar to llvm::CCState, but for Clang.
551struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000552 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000553
554 unsigned CC;
555 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000556 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000557};
558
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559/// X86_32ABIInfo - The X86-32 ABI information.
560class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000561 enum Class {
562 Integer,
563 Float
564 };
565
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000566 static const unsigned MinABIStackAlignInBytes = 4;
567
David Chisnallde3a0692009-08-17 23:08:21 +0000568 bool IsDarwinVectorABI;
569 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000570 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000571 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572
573 static bool isRegisterSize(unsigned Size) {
574 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
575 }
576
Reid Kleckner80944df2014-10-31 22:00:51 +0000577 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
578 // FIXME: Assumes vectorcall is in use.
579 return isX86VectorTypeForVectorCall(getContext(), Ty);
580 }
581
582 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
583 uint64_t NumMembers) const override {
584 // FIXME: Assumes vectorcall is in use.
585 return isX86VectorCallAggregateSmallEnough(NumMembers);
586 }
587
Reid Kleckner40ca9132014-05-13 22:05:45 +0000588 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000589
Daniel Dunbar557893d2010-04-21 19:10:51 +0000590 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
591 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000592 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
593
594 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000595
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000596 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000597 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000598
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000599 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000600 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000601 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
602 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000603
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000604 /// \brief Rewrite the function info so that all memory arguments use
605 /// inalloca.
606 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
607
608 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
609 unsigned &StackOffset, ABIArgInfo &Info,
610 QualType Type) const;
611
Rafael Espindola75419dc2012-07-23 23:30:29 +0000612public:
613
Craig Topper4f12f102014-03-12 06:41:41 +0000614 void computeInfo(CGFunctionInfo &FI) const override;
615 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
616 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000617
Chad Rosier651c1832013-03-25 21:00:27 +0000618 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000619 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000620 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000621 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000623
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000624class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
625public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000626 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000627 bool d, bool p, bool w, unsigned r)
628 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000629
John McCall1fe2a8c2013-06-18 02:46:29 +0000630 static bool isStructReturnInRegABI(
631 const llvm::Triple &Triple, const CodeGenOptions &Opts);
632
Charles Davis4ea31ab2010-02-13 15:54:06 +0000633 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000634 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000635
Craig Topper4f12f102014-03-12 06:41:41 +0000636 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000637 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000638 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000639 return 4;
640 }
641
642 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000643 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000644
Jay Foad7c57be32011-07-11 09:56:20 +0000645 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000646 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000647 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000648 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
649 }
650
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000651 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
652 std::string &Constraints,
653 std::vector<llvm::Type *> &ResultRegTypes,
654 std::vector<llvm::Type *> &ResultTruncRegTypes,
655 std::vector<LValue> &ResultRegDests,
656 std::string &AsmString,
657 unsigned NumOutputs) const override;
658
Craig Topper4f12f102014-03-12 06:41:41 +0000659 llvm::Constant *
660 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000661 unsigned Sig = (0xeb << 0) | // jmp rel8
662 (0x06 << 8) | // .+0x08
663 ('F' << 16) |
664 ('T' << 24);
665 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
666 }
667
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000668};
669
670}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000671
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000672/// Rewrite input constraint references after adding some output constraints.
673/// In the case where there is one output and one input and we add one output,
674/// we need to replace all operand references greater than or equal to 1:
675/// mov $0, $1
676/// mov eax, $1
677/// The result will be:
678/// mov $0, $2
679/// mov eax, $2
680static void rewriteInputConstraintReferences(unsigned FirstIn,
681 unsigned NumNewOuts,
682 std::string &AsmString) {
683 std::string Buf;
684 llvm::raw_string_ostream OS(Buf);
685 size_t Pos = 0;
686 while (Pos < AsmString.size()) {
687 size_t DollarStart = AsmString.find('$', Pos);
688 if (DollarStart == std::string::npos)
689 DollarStart = AsmString.size();
690 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
691 if (DollarEnd == std::string::npos)
692 DollarEnd = AsmString.size();
693 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
694 Pos = DollarEnd;
695 size_t NumDollars = DollarEnd - DollarStart;
696 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
697 // We have an operand reference.
698 size_t DigitStart = Pos;
699 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
700 if (DigitEnd == std::string::npos)
701 DigitEnd = AsmString.size();
702 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
703 unsigned OperandIndex;
704 if (!OperandStr.getAsInteger(10, OperandIndex)) {
705 if (OperandIndex >= FirstIn)
706 OperandIndex += NumNewOuts;
707 OS << OperandIndex;
708 } else {
709 OS << OperandStr;
710 }
711 Pos = DigitEnd;
712 }
713 }
714 AsmString = std::move(OS.str());
715}
716
717/// Add output constraints for EAX:EDX because they are return registers.
718void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
719 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
720 std::vector<llvm::Type *> &ResultRegTypes,
721 std::vector<llvm::Type *> &ResultTruncRegTypes,
722 std::vector<LValue> &ResultRegDests, std::string &AsmString,
723 unsigned NumOutputs) const {
724 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
725
726 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
727 // larger.
728 if (!Constraints.empty())
729 Constraints += ',';
730 if (RetWidth <= 32) {
731 Constraints += "={eax}";
732 ResultRegTypes.push_back(CGF.Int32Ty);
733 } else {
734 // Use the 'A' constraint for EAX:EDX.
735 Constraints += "=A";
736 ResultRegTypes.push_back(CGF.Int64Ty);
737 }
738
739 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
740 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
741 ResultTruncRegTypes.push_back(CoerceTy);
742
743 // Coerce the integer by bitcasting the return slot pointer.
744 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
745 CoerceTy->getPointerTo()));
746 ResultRegDests.push_back(ReturnSlot);
747
748 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
749}
750
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000751/// shouldReturnTypeInRegister - Determine if the given type should be
752/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000753bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
754 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000755 uint64_t Size = Context.getTypeSize(Ty);
756
757 // Type must be register sized.
758 if (!isRegisterSize(Size))
759 return false;
760
761 if (Ty->isVectorType()) {
762 // 64- and 128- bit vectors inside structures are not returned in
763 // registers.
764 if (Size == 64 || Size == 128)
765 return false;
766
767 return true;
768 }
769
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000770 // If this is a builtin, pointer, enum, complex type, member pointer, or
771 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000772 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000773 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000774 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000775 return true;
776
777 // Arrays are treated like records.
778 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000779 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000780
781 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000782 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000783 if (!RT) return false;
784
Anders Carlsson40446e82010-01-27 03:25:19 +0000785 // FIXME: Traverse bases here too.
786
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000787 // Structure types are passed in register if all fields would be
788 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000789 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000790 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000791 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000792 continue;
793
794 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000795 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000796 return false;
797 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798 return true;
799}
800
Reid Kleckner661f35b2014-01-18 01:12:41 +0000801ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
802 // If the return value is indirect, then the hidden argument is consuming one
803 // integer register.
804 if (State.FreeRegs) {
805 --State.FreeRegs;
806 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
807 }
808 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
809}
810
Reid Kleckner40ca9132014-05-13 22:05:45 +0000811ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000812 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000813 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000814
Reid Kleckner80944df2014-10-31 22:00:51 +0000815 const Type *Base = nullptr;
816 uint64_t NumElts = 0;
817 if (State.CC == llvm::CallingConv::X86_VectorCall &&
818 isHomogeneousAggregate(RetTy, Base, NumElts)) {
819 // The LLVM struct type for such an aggregate should lower properly.
820 return ABIArgInfo::getDirect();
821 }
822
Chris Lattner458b2aa2010-07-29 02:16:43 +0000823 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000824 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000825 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000826 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000827
828 // 128-bit vectors are a special case; they are returned in
829 // registers and we need to make sure to pick a type the LLVM
830 // backend will like.
831 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000832 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000833 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000834
835 // Always return in register if it fits in a general purpose
836 // register, or if it is 64 bits and has a single element.
837 if ((Size == 8 || Size == 16 || Size == 32) ||
838 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000839 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000840 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000841
Reid Kleckner661f35b2014-01-18 01:12:41 +0000842 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000843 }
844
845 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000846 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000847
John McCalla1dee5302010-08-22 10:59:02 +0000848 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000849 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000850 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000851 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000852 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000853 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000854
David Chisnallde3a0692009-08-17 23:08:21 +0000855 // If specified, structs and unions are always indirect.
856 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000857 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000858
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000859 // Small structures which are register sized are generally returned
860 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000861 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000862 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000863
864 // As a special-case, if the struct is a "single-element" struct, and
865 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000866 // floating-point register. (MSVC does not apply this special case.)
867 // We apply a similar transformation for pointer types to improve the
868 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000869 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000870 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000871 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000872 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
873
874 // FIXME: We should be able to narrow this integer in cases with dead
875 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000876 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000877 }
878
Reid Kleckner661f35b2014-01-18 01:12:41 +0000879 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000880 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000881
Chris Lattner458b2aa2010-07-29 02:16:43 +0000882 // Treat an enum type as its underlying type.
883 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
884 RetTy = EnumTy->getDecl()->getIntegerType();
885
886 return (RetTy->isPromotableIntegerType() ?
887 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000888}
889
Eli Friedman7919bea2012-06-05 19:40:46 +0000890static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
891 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
892}
893
Daniel Dunbared23de32010-09-16 20:42:00 +0000894static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
895 const RecordType *RT = Ty->getAs<RecordType>();
896 if (!RT)
897 return 0;
898 const RecordDecl *RD = RT->getDecl();
899
900 // If this is a C++ record, check the bases first.
901 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000902 for (const auto &I : CXXRD->bases())
903 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000904 return false;
905
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000906 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000907 QualType FT = i->getType();
908
Eli Friedman7919bea2012-06-05 19:40:46 +0000909 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000910 return true;
911
912 if (isRecordWithSSEVectorType(Context, FT))
913 return true;
914 }
915
916 return false;
917}
918
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000919unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
920 unsigned Align) const {
921 // Otherwise, if the alignment is less than or equal to the minimum ABI
922 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000923 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000924 return 0; // Use default alignment.
925
926 // On non-Darwin, the stack type alignment is always 4.
927 if (!IsDarwinVectorABI) {
928 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000929 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000930 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000931
Daniel Dunbared23de32010-09-16 20:42:00 +0000932 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000933 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
934 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000935 return 16;
936
937 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000938}
939
Rafael Espindola703c47f2012-10-19 05:04:37 +0000940ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000941 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000942 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000943 if (State.FreeRegs) {
944 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000945 return ABIArgInfo::getIndirectInReg(0, false);
946 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000947 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000948 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000949
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000950 // Compute the byval alignment.
951 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
952 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
953 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000954 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000955
956 // If the stack alignment is less than the type alignment, realign the
957 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000958 bool Realign = TypeAlign > StackAlign;
959 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000960}
961
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000962X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
963 const Type *T = isSingleElementStruct(Ty, getContext());
964 if (!T)
965 T = Ty.getTypePtr();
966
967 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
968 BuiltinType::Kind K = BT->getKind();
969 if (K == BuiltinType::Float || K == BuiltinType::Double)
970 return Float;
971 }
972 return Integer;
973}
974
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
976 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000977 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000978 Class C = classify(Ty);
979 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000980 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000981
Rafael Espindola077dd592012-10-24 01:58:58 +0000982 unsigned Size = getContext().getTypeSize(Ty);
983 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000984
985 if (SizeInRegs == 0)
986 return false;
987
Reid Kleckner661f35b2014-01-18 01:12:41 +0000988 if (SizeInRegs > State.FreeRegs) {
989 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000990 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000991 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000992
Reid Kleckner661f35b2014-01-18 01:12:41 +0000993 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000994
Reid Kleckner80944df2014-10-31 22:00:51 +0000995 if (State.CC == llvm::CallingConv::X86_FastCall ||
996 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000997 if (Size > 32)
998 return false;
999
1000 if (Ty->isIntegralOrEnumerationType())
1001 return true;
1002
1003 if (Ty->isPointerType())
1004 return true;
1005
1006 if (Ty->isReferenceType())
1007 return true;
1008
Reid Kleckner661f35b2014-01-18 01:12:41 +00001009 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001010 NeedsPadding = true;
1011
Rafael Espindola077dd592012-10-24 01:58:58 +00001012 return false;
1013 }
1014
Rafael Espindola703c47f2012-10-19 05:04:37 +00001015 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001016}
1017
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001018ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1019 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001020 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001021
Reid Klecknerb1be6832014-11-15 01:41:41 +00001022 Ty = useFirstFieldIfTransparentUnion(Ty);
1023
Reid Kleckner80944df2014-10-31 22:00:51 +00001024 // Check with the C++ ABI first.
1025 const RecordType *RT = Ty->getAs<RecordType>();
1026 if (RT) {
1027 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1028 if (RAA == CGCXXABI::RAA_Indirect) {
1029 return getIndirectResult(Ty, false, State);
1030 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1031 // The field index doesn't matter, we'll fix it up later.
1032 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1033 }
1034 }
1035
1036 // vectorcall adds the concept of a homogenous vector aggregate, similar
1037 // to other targets.
1038 const Type *Base = nullptr;
1039 uint64_t NumElts = 0;
1040 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1041 isHomogeneousAggregate(Ty, Base, NumElts)) {
1042 if (State.FreeSSERegs >= NumElts) {
1043 State.FreeSSERegs -= NumElts;
1044 if (Ty->isBuiltinType() || Ty->isVectorType())
1045 return ABIArgInfo::getDirect();
1046 return ABIArgInfo::getExpand();
1047 }
1048 return getIndirectResult(Ty, /*ByVal=*/false, State);
1049 }
1050
1051 if (isAggregateTypeForABI(Ty)) {
1052 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001053 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001054 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001055 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001056
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001057 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001058 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001059 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001060 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001061
Eli Friedman9f061a32011-11-18 00:28:11 +00001062 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001063 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001064 return ABIArgInfo::getIgnore();
1065
Rafael Espindolafad28de2012-10-24 01:59:00 +00001066 llvm::LLVMContext &LLVMContext = getVMContext();
1067 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1068 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001069 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001070 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001071 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001072 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1073 return ABIArgInfo::getDirectInReg(Result);
1074 }
Craig Topper8a13c412014-05-21 05:09:00 +00001075 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001076
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001077 // Expand small (<= 128-bit) record types when we know that the stack layout
1078 // of those arguments will match the struct. This is important because the
1079 // LLVM backend isn't smart enough to remove byval, which inhibits many
1080 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001081 if (getContext().getTypeSize(Ty) <= 4*32 &&
1082 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001083 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001084 State.CC == llvm::CallingConv::X86_FastCall ||
1085 State.CC == llvm::CallingConv::X86_VectorCall,
1086 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001087
Reid Kleckner661f35b2014-01-18 01:12:41 +00001088 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001089 }
1090
Chris Lattnerd774ae92010-08-26 20:05:13 +00001091 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001092 // On Darwin, some vectors are passed in memory, we handle this by passing
1093 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001094 if (IsDarwinVectorABI) {
1095 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001096 if ((Size == 8 || Size == 16 || Size == 32) ||
1097 (Size == 64 && VT->getNumElements() == 1))
1098 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1099 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001100 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001101
Chad Rosier651c1832013-03-25 21:00:27 +00001102 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1103 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001104
Chris Lattnerd774ae92010-08-26 20:05:13 +00001105 return ABIArgInfo::getDirect();
1106 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001107
1108
Chris Lattner458b2aa2010-07-29 02:16:43 +00001109 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1110 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001111
Rafael Espindolafad28de2012-10-24 01:59:00 +00001112 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001113 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001114
1115 if (Ty->isPromotableIntegerType()) {
1116 if (InReg)
1117 return ABIArgInfo::getExtendInReg();
1118 return ABIArgInfo::getExtend();
1119 }
1120 if (InReg)
1121 return ABIArgInfo::getDirectInReg();
1122 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001123}
1124
Rafael Espindolaa6472962012-07-24 00:01:07 +00001125void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001126 CCState State(FI.getCallingConvention());
1127 if (State.CC == llvm::CallingConv::X86_FastCall)
1128 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001129 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1130 State.FreeRegs = 2;
1131 State.FreeSSERegs = 6;
1132 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001133 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001134 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001135 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001136
Reid Kleckner677539d2014-07-10 01:58:55 +00001137 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001138 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001139 } else if (FI.getReturnInfo().isIndirect()) {
1140 // The C++ ABI is not aware of register usage, so we have to check if the
1141 // return value was sret and put it in a register ourselves if appropriate.
1142 if (State.FreeRegs) {
1143 --State.FreeRegs; // The sret parameter consumes a register.
1144 FI.getReturnInfo().setInReg(true);
1145 }
1146 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001147
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001148 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001149 for (auto &I : FI.arguments()) {
1150 I.info = classifyArgumentType(I.type, State);
1151 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001152 }
1153
1154 // If we needed to use inalloca for any argument, do a second pass and rewrite
1155 // all the memory arguments to use inalloca.
1156 if (UsedInAlloca)
1157 rewriteWithInAlloca(FI);
1158}
1159
1160void
1161X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1162 unsigned &StackOffset,
1163 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001164 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1165 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1166 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1167 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1168
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001169 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1170 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001171 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001172 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001173 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001174 unsigned NumBytes = StackOffset - OldOffset;
1175 assert(NumBytes);
1176 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1177 Ty = llvm::ArrayType::get(Ty, NumBytes);
1178 FrameFields.push_back(Ty);
1179 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001180}
1181
Reid Kleckner852361d2014-07-26 00:12:26 +00001182static bool isArgInAlloca(const ABIArgInfo &Info) {
1183 // Leave ignored and inreg arguments alone.
1184 switch (Info.getKind()) {
1185 case ABIArgInfo::InAlloca:
1186 return true;
1187 case ABIArgInfo::Indirect:
1188 assert(Info.getIndirectByVal());
1189 return true;
1190 case ABIArgInfo::Ignore:
1191 return false;
1192 case ABIArgInfo::Direct:
1193 case ABIArgInfo::Extend:
1194 case ABIArgInfo::Expand:
1195 if (Info.getInReg())
1196 return false;
1197 return true;
1198 }
1199 llvm_unreachable("invalid enum");
1200}
1201
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001202void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1203 assert(IsWin32StructABI && "inalloca only supported on win32");
1204
1205 // Build a packed struct type for all of the arguments in memory.
1206 SmallVector<llvm::Type *, 6> FrameFields;
1207
1208 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001209 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1210
1211 // Put 'this' into the struct before 'sret', if necessary.
1212 bool IsThisCall =
1213 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1214 ABIArgInfo &Ret = FI.getReturnInfo();
1215 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1216 isArgInAlloca(I->info)) {
1217 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1218 ++I;
1219 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001220
1221 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001222 if (Ret.isIndirect() && !Ret.getInReg()) {
1223 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1224 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001225 // On Windows, the hidden sret parameter is always returned in eax.
1226 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001227 }
1228
1229 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001230 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001231 ++I;
1232
1233 // Put arguments passed in memory into the struct.
1234 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001235 if (isArgInAlloca(I->info))
1236 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001237 }
1238
1239 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1240 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001241}
1242
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001243llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1244 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001245 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001246
1247 CGBuilderTy &Builder = CGF.Builder;
1248 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1249 "ap");
1250 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001251
1252 // Compute if the address needs to be aligned
1253 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1254 Align = getTypeStackAlignInBytes(Ty, Align);
1255 Align = std::max(Align, 4U);
1256 if (Align > 4) {
1257 // addr = (addr + align - 1) & -align;
1258 llvm::Value *Offset =
1259 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1260 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1261 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1262 CGF.Int32Ty);
1263 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1264 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1265 Addr->getType(),
1266 "ap.cur.aligned");
1267 }
1268
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001270 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001271 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1272
1273 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001274 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001276 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001277 "ap.next");
1278 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1279
1280 return AddrTyped;
1281}
1282
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001283bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1284 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1285 assert(Triple.getArch() == llvm::Triple::x86);
1286
1287 switch (Opts.getStructReturnConvention()) {
1288 case CodeGenOptions::SRCK_Default:
1289 break;
1290 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1291 return false;
1292 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1293 return true;
1294 }
1295
1296 if (Triple.isOSDarwin())
1297 return true;
1298
1299 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001300 case llvm::Triple::DragonFly:
1301 case llvm::Triple::FreeBSD:
1302 case llvm::Triple::OpenBSD:
1303 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001304 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001305 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001306 default:
1307 return false;
1308 }
1309}
1310
Charles Davis4ea31ab2010-02-13 15:54:06 +00001311void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1312 llvm::GlobalValue *GV,
1313 CodeGen::CodeGenModule &CGM) const {
1314 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1315 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1316 // Get the LLVM function.
1317 llvm::Function *Fn = cast<llvm::Function>(GV);
1318
1319 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001320 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001321 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001322 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1323 llvm::AttributeSet::get(CGM.getLLVMContext(),
1324 llvm::AttributeSet::FunctionIndex,
1325 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001326 }
1327 }
1328}
1329
John McCallbeec5a02010-03-06 00:35:14 +00001330bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1331 CodeGen::CodeGenFunction &CGF,
1332 llvm::Value *Address) const {
1333 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001334
Chris Lattnerece04092012-02-07 00:39:47 +00001335 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001336
John McCallbeec5a02010-03-06 00:35:14 +00001337 // 0-7 are the eight integer registers; the order is different
1338 // on Darwin (for EH), but the range is the same.
1339 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001340 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001341
John McCallc8e01702013-04-16 22:48:15 +00001342 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001343 // 12-16 are st(0..4). Not sure why we stop at 4.
1344 // These have size 16, which is sizeof(long double) on
1345 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001346 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001347 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001348
John McCallbeec5a02010-03-06 00:35:14 +00001349 } else {
1350 // 9 is %eflags, which doesn't get a size on Darwin for some
1351 // reason.
1352 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1353
1354 // 11-16 are st(0..5). Not sure why we stop at 5.
1355 // These have size 12, which is sizeof(long double) on
1356 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001357 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001358 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1359 }
John McCallbeec5a02010-03-06 00:35:14 +00001360
1361 return false;
1362}
1363
Chris Lattner0cf24192010-06-28 20:05:43 +00001364//===----------------------------------------------------------------------===//
1365// X86-64 ABI Implementation
1366//===----------------------------------------------------------------------===//
1367
1368
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001369namespace {
1370/// X86_64ABIInfo - The X86_64 ABI information.
1371class X86_64ABIInfo : public ABIInfo {
1372 enum Class {
1373 Integer = 0,
1374 SSE,
1375 SSEUp,
1376 X87,
1377 X87Up,
1378 ComplexX87,
1379 NoClass,
1380 Memory
1381 };
1382
1383 /// merge - Implement the X86_64 ABI merging algorithm.
1384 ///
1385 /// Merge an accumulating classification \arg Accum with a field
1386 /// classification \arg Field.
1387 ///
1388 /// \param Accum - The accumulating classification. This should
1389 /// always be either NoClass or the result of a previous merge
1390 /// call. In addition, this should never be Memory (the caller
1391 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001392 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001393
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001394 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1395 ///
1396 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1397 /// final MEMORY or SSE classes when necessary.
1398 ///
1399 /// \param AggregateSize - The size of the current aggregate in
1400 /// the classification process.
1401 ///
1402 /// \param Lo - The classification for the parts of the type
1403 /// residing in the low word of the containing object.
1404 ///
1405 /// \param Hi - The classification for the parts of the type
1406 /// residing in the higher words of the containing object.
1407 ///
1408 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1409
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001410 /// classify - Determine the x86_64 register classes in which the
1411 /// given type T should be passed.
1412 ///
1413 /// \param Lo - The classification for the parts of the type
1414 /// residing in the low word of the containing object.
1415 ///
1416 /// \param Hi - The classification for the parts of the type
1417 /// residing in the high word of the containing object.
1418 ///
1419 /// \param OffsetBase - The bit offset of this type in the
1420 /// containing object. Some parameters are classified different
1421 /// depending on whether they straddle an eightbyte boundary.
1422 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001423 /// \param isNamedArg - Whether the argument in question is a "named"
1424 /// argument, as used in AMD64-ABI 3.5.7.
1425 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001426 /// If a word is unused its result will be NoClass; if a type should
1427 /// be passed in Memory then at least the classification of \arg Lo
1428 /// will be Memory.
1429 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001430 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001431 ///
1432 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1433 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001434 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1435 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001436
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001437 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001438 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1439 unsigned IROffset, QualType SourceTy,
1440 unsigned SourceOffset) const;
1441 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1442 unsigned IROffset, QualType SourceTy,
1443 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001444
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001445 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001446 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001447 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001448
1449 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001450 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001451 ///
1452 /// \param freeIntRegs - The number of free integer registers remaining
1453 /// available.
1454 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001455
Chris Lattner458b2aa2010-07-29 02:16:43 +00001456 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001457
Bill Wendling5cd41c42010-10-18 03:41:31 +00001458 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001459 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001460 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001461 unsigned &neededSSE,
1462 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001463
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001464 bool IsIllegalVectorType(QualType Ty) const;
1465
John McCalle0fda732011-04-21 01:20:55 +00001466 /// The 0.98 ABI revision clarified a lot of ambiguities,
1467 /// unfortunately in ways that were not always consistent with
1468 /// certain previous compilers. In particular, platforms which
1469 /// required strict binary compatibility with older versions of GCC
1470 /// may need to exempt themselves.
1471 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001472 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001473 }
1474
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001475 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001476 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1477 // 64-bit hardware.
1478 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001479
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001481 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001482 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001483 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001484 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001485
John McCalla729c622012-02-17 03:33:10 +00001486 bool isPassedUsingAVXType(QualType type) const {
1487 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001488 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001489 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1490 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001491 if (info.isDirect()) {
1492 llvm::Type *ty = info.getCoerceToType();
1493 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1494 return (vectorTy->getBitWidth() > 128);
1495 }
1496 return false;
1497 }
1498
Craig Topper4f12f102014-03-12 06:41:41 +00001499 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001500
Craig Topper4f12f102014-03-12 06:41:41 +00001501 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1502 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001503};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001504
Chris Lattner04dc9572010-08-31 16:44:54 +00001505/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001506class WinX86_64ABIInfo : public ABIInfo {
1507
Reid Kleckner80944df2014-10-31 22:00:51 +00001508 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1509 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001510
Chris Lattner04dc9572010-08-31 16:44:54 +00001511public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001512 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1513
Craig Topper4f12f102014-03-12 06:41:41 +00001514 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001515
Craig Topper4f12f102014-03-12 06:41:41 +00001516 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1517 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001518
1519 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1520 // FIXME: Assumes vectorcall is in use.
1521 return isX86VectorTypeForVectorCall(getContext(), Ty);
1522 }
1523
1524 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1525 uint64_t NumMembers) const override {
1526 // FIXME: Assumes vectorcall is in use.
1527 return isX86VectorCallAggregateSmallEnough(NumMembers);
1528 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001529};
1530
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001531class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001532 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001533public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001534 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001535 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001536
John McCalla729c622012-02-17 03:33:10 +00001537 const X86_64ABIInfo &getABIInfo() const {
1538 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1539 }
1540
Craig Topper4f12f102014-03-12 06:41:41 +00001541 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001542 return 7;
1543 }
1544
1545 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001546 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001547 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001548
John McCall943fae92010-05-27 06:19:26 +00001549 // 0-15 are the 16 integer registers.
1550 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001551 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001552 return false;
1553 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001554
Jay Foad7c57be32011-07-11 09:56:20 +00001555 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001556 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001557 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001558 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1559 }
1560
John McCalla729c622012-02-17 03:33:10 +00001561 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001562 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001563 // The default CC on x86-64 sets %al to the number of SSA
1564 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001565 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001566 // that when AVX types are involved: the ABI explicitly states it is
1567 // undefined, and it doesn't work in practice because of how the ABI
1568 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001569 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001570 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001571 for (CallArgList::const_iterator
1572 it = args.begin(), ie = args.end(); it != ie; ++it) {
1573 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1574 HasAVXType = true;
1575 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001576 }
1577 }
John McCalla729c622012-02-17 03:33:10 +00001578
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001579 if (!HasAVXType)
1580 return true;
1581 }
John McCallcbc038a2011-09-21 08:08:30 +00001582
John McCalla729c622012-02-17 03:33:10 +00001583 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001584 }
1585
Craig Topper4f12f102014-03-12 06:41:41 +00001586 llvm::Constant *
1587 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001588 unsigned Sig = (0xeb << 0) | // jmp rel8
1589 (0x0a << 8) | // .+0x0c
1590 ('F' << 16) |
1591 ('T' << 24);
1592 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1593 }
1594
Alexander Musman09184fe2014-09-30 05:29:28 +00001595 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1596 return HasAVX ? 32 : 16;
1597 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001598};
1599
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001600static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1601 // If the argument does not end in .lib, automatically add the suffix. This
1602 // matches the behavior of MSVC.
1603 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001604 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001605 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001606 return ArgStr;
1607}
1608
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001609class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1610public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001611 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1612 bool d, bool p, bool w, unsigned RegParms)
1613 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001614
1615 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001616 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001617 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001618 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001619 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001620
1621 void getDetectMismatchOption(llvm::StringRef Name,
1622 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001623 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001624 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001625 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001626};
1627
Chris Lattner04dc9572010-08-31 16:44:54 +00001628class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001629 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001630public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001631 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1632 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001633
Craig Topper4f12f102014-03-12 06:41:41 +00001634 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001635 return 7;
1636 }
1637
1638 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001639 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001640 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001641
Chris Lattner04dc9572010-08-31 16:44:54 +00001642 // 0-15 are the 16 integer registers.
1643 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001644 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001645 return false;
1646 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001647
1648 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001649 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001650 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001651 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001652 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001653
1654 void getDetectMismatchOption(llvm::StringRef Name,
1655 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001656 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001657 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001658 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001659
1660 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1661 return HasAVX ? 32 : 16;
1662 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001663};
1664
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001665}
1666
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001667void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1668 Class &Hi) const {
1669 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1670 //
1671 // (a) If one of the classes is Memory, the whole argument is passed in
1672 // memory.
1673 //
1674 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1675 // memory.
1676 //
1677 // (c) If the size of the aggregate exceeds two eightbytes and the first
1678 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1679 // argument is passed in memory. NOTE: This is necessary to keep the
1680 // ABI working for processors that don't support the __m256 type.
1681 //
1682 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1683 //
1684 // Some of these are enforced by the merging logic. Others can arise
1685 // only with unions; for example:
1686 // union { _Complex double; unsigned; }
1687 //
1688 // Note that clauses (b) and (c) were added in 0.98.
1689 //
1690 if (Hi == Memory)
1691 Lo = Memory;
1692 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1693 Lo = Memory;
1694 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1695 Lo = Memory;
1696 if (Hi == SSEUp && Lo != SSE)
1697 Hi = SSE;
1698}
1699
Chris Lattnerd776fb12010-06-28 21:43:59 +00001700X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001701 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1702 // classified recursively so that always two fields are
1703 // considered. The resulting class is calculated according to
1704 // the classes of the fields in the eightbyte:
1705 //
1706 // (a) If both classes are equal, this is the resulting class.
1707 //
1708 // (b) If one of the classes is NO_CLASS, the resulting class is
1709 // the other class.
1710 //
1711 // (c) If one of the classes is MEMORY, the result is the MEMORY
1712 // class.
1713 //
1714 // (d) If one of the classes is INTEGER, the result is the
1715 // INTEGER.
1716 //
1717 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1718 // MEMORY is used as class.
1719 //
1720 // (f) Otherwise class SSE is used.
1721
1722 // Accum should never be memory (we should have returned) or
1723 // ComplexX87 (because this cannot be passed in a structure).
1724 assert((Accum != Memory && Accum != ComplexX87) &&
1725 "Invalid accumulated classification during merge.");
1726 if (Accum == Field || Field == NoClass)
1727 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001728 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001729 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001730 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001731 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001732 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001733 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001734 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1735 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001736 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001737 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001738}
1739
Chris Lattner5c740f12010-06-30 19:14:05 +00001740void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001741 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001742 // FIXME: This code can be simplified by introducing a simple value class for
1743 // Class pairs with appropriate constructor methods for the various
1744 // situations.
1745
1746 // FIXME: Some of the split computations are wrong; unaligned vectors
1747 // shouldn't be passed in registers for example, so there is no chance they
1748 // can straddle an eightbyte. Verify & simplify.
1749
1750 Lo = Hi = NoClass;
1751
1752 Class &Current = OffsetBase < 64 ? Lo : Hi;
1753 Current = Memory;
1754
John McCall9dd450b2009-09-21 23:43:11 +00001755 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001756 BuiltinType::Kind k = BT->getKind();
1757
1758 if (k == BuiltinType::Void) {
1759 Current = NoClass;
1760 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1761 Lo = Integer;
1762 Hi = Integer;
1763 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1764 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001765 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1766 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001767 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001768 Current = SSE;
1769 } else if (k == BuiltinType::LongDouble) {
1770 Lo = X87;
1771 Hi = X87Up;
1772 }
1773 // FIXME: _Decimal32 and _Decimal64 are SSE.
1774 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001775 return;
1776 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001777
Chris Lattnerd776fb12010-06-28 21:43:59 +00001778 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001779 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001780 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001781 return;
1782 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001783
Chris Lattnerd776fb12010-06-28 21:43:59 +00001784 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001785 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001786 return;
1787 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001788
Chris Lattnerd776fb12010-06-28 21:43:59 +00001789 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001790 if (Ty->isMemberFunctionPointerType()) {
1791 if (Has64BitPointers) {
1792 // If Has64BitPointers, this is an {i64, i64}, so classify both
1793 // Lo and Hi now.
1794 Lo = Hi = Integer;
1795 } else {
1796 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1797 // straddles an eightbyte boundary, Hi should be classified as well.
1798 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1799 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1800 if (EB_FuncPtr != EB_ThisAdj) {
1801 Lo = Hi = Integer;
1802 } else {
1803 Current = Integer;
1804 }
1805 }
1806 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001807 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001808 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001809 return;
1810 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001811
Chris Lattnerd776fb12010-06-28 21:43:59 +00001812 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001813 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001814 if (Size == 32) {
1815 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1816 // float> as integer.
1817 Current = Integer;
1818
1819 // If this type crosses an eightbyte boundary, it should be
1820 // split.
1821 uint64_t EB_Real = (OffsetBase) / 64;
1822 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1823 if (EB_Real != EB_Imag)
1824 Hi = Lo;
1825 } else if (Size == 64) {
1826 // gcc passes <1 x double> in memory. :(
1827 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1828 return;
1829
1830 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001831 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001832 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1833 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1834 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001835 Current = Integer;
1836 else
1837 Current = SSE;
1838
1839 // If this type crosses an eightbyte boundary, it should be
1840 // split.
1841 if (OffsetBase && OffsetBase != 64)
1842 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001843 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001844 // Arguments of 256-bits are split into four eightbyte chunks. The
1845 // least significant one belongs to class SSE and all the others to class
1846 // SSEUP. The original Lo and Hi design considers that types can't be
1847 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1848 // This design isn't correct for 256-bits, but since there're no cases
1849 // where the upper parts would need to be inspected, avoid adding
1850 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001851 //
1852 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1853 // registers if they are "named", i.e. not part of the "..." of a
1854 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001855 Lo = SSE;
1856 Hi = SSEUp;
1857 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001858 return;
1859 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001860
Chris Lattnerd776fb12010-06-28 21:43:59 +00001861 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001862 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001863
Chris Lattner2b037972010-07-29 02:01:43 +00001864 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001865 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001866 if (Size <= 64)
1867 Current = Integer;
1868 else if (Size <= 128)
1869 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001870 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001871 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001872 else if (ET == getContext().DoubleTy ||
1873 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001874 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001875 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001876 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001877 Current = ComplexX87;
1878
1879 // If this complex type crosses an eightbyte boundary then it
1880 // should be split.
1881 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001882 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001883 if (Hi == NoClass && EB_Real != EB_Imag)
1884 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001885
Chris Lattnerd776fb12010-06-28 21:43:59 +00001886 return;
1887 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001888
Chris Lattner2b037972010-07-29 02:01:43 +00001889 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001890 // Arrays are treated like structures.
1891
Chris Lattner2b037972010-07-29 02:01:43 +00001892 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001893
1894 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001895 // than four eightbytes, ..., it has class MEMORY.
1896 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001897 return;
1898
1899 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1900 // fields, it has class MEMORY.
1901 //
1902 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001903 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001904 return;
1905
1906 // Otherwise implement simplified merge. We could be smarter about
1907 // this, but it isn't worth it and would be harder to verify.
1908 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001909 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001910 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001911
1912 // The only case a 256-bit wide vector could be used is when the array
1913 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1914 // to work for sizes wider than 128, early check and fallback to memory.
1915 if (Size > 128 && EltSize != 256)
1916 return;
1917
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001918 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1919 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001920 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001921 Lo = merge(Lo, FieldLo);
1922 Hi = merge(Hi, FieldHi);
1923 if (Lo == Memory || Hi == Memory)
1924 break;
1925 }
1926
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001927 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001928 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001929 return;
1930 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001931
Chris Lattnerd776fb12010-06-28 21:43:59 +00001932 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001933 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001934
1935 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001936 // than four eightbytes, ..., it has class MEMORY.
1937 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001938 return;
1939
Anders Carlsson20759ad2009-09-16 15:53:40 +00001940 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1941 // copy constructor or a non-trivial destructor, it is passed by invisible
1942 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001943 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001944 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001945
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001946 const RecordDecl *RD = RT->getDecl();
1947
1948 // Assume variable sized types are passed in memory.
1949 if (RD->hasFlexibleArrayMember())
1950 return;
1951
Chris Lattner2b037972010-07-29 02:01:43 +00001952 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001953
1954 // Reset Lo class, this will be recomputed.
1955 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001956
1957 // If this is a C++ record, classify the bases first.
1958 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001959 for (const auto &I : CXXRD->bases()) {
1960 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001961 "Unexpected base class!");
1962 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001963 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001964
1965 // Classify this field.
1966 //
1967 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1968 // single eightbyte, each is classified separately. Each eightbyte gets
1969 // initialized to class NO_CLASS.
1970 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001971 uint64_t Offset =
1972 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001973 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001974 Lo = merge(Lo, FieldLo);
1975 Hi = merge(Hi, FieldHi);
1976 if (Lo == Memory || Hi == Memory)
1977 break;
1978 }
1979 }
1980
1981 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001982 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001983 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001984 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001985 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1986 bool BitField = i->isBitField();
1987
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001988 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1989 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001990 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001991 // The only case a 256-bit wide vector could be used is when the struct
1992 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1993 // to work for sizes wider than 128, early check and fallback to memory.
1994 //
1995 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1996 Lo = Memory;
1997 return;
1998 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001999 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002000 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002001 Lo = Memory;
2002 return;
2003 }
2004
2005 // Classify this field.
2006 //
2007 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2008 // exceeds a single eightbyte, each is classified
2009 // separately. Each eightbyte gets initialized to class
2010 // NO_CLASS.
2011 Class FieldLo, FieldHi;
2012
2013 // Bit-fields require special handling, they do not force the
2014 // structure to be passed in memory even if unaligned, and
2015 // therefore they can straddle an eightbyte.
2016 if (BitField) {
2017 // Ignore padding bit-fields.
2018 if (i->isUnnamedBitfield())
2019 continue;
2020
2021 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002022 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002023
2024 uint64_t EB_Lo = Offset / 64;
2025 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002026
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002027 if (EB_Lo) {
2028 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2029 FieldLo = NoClass;
2030 FieldHi = Integer;
2031 } else {
2032 FieldLo = Integer;
2033 FieldHi = EB_Hi ? Integer : NoClass;
2034 }
2035 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002036 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002037 Lo = merge(Lo, FieldLo);
2038 Hi = merge(Hi, FieldHi);
2039 if (Lo == Memory || Hi == Memory)
2040 break;
2041 }
2042
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002043 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002044 }
2045}
2046
Chris Lattner22a931e2010-06-29 06:01:59 +00002047ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002048 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2049 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002050 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002051 // Treat an enum type as its underlying type.
2052 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2053 Ty = EnumTy->getDecl()->getIntegerType();
2054
2055 return (Ty->isPromotableIntegerType() ?
2056 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2057 }
2058
2059 return ABIArgInfo::getIndirect(0);
2060}
2061
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002062bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2063 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2064 uint64_t Size = getContext().getTypeSize(VecTy);
2065 unsigned LargestVector = HasAVX ? 256 : 128;
2066 if (Size <= 64 || Size > LargestVector)
2067 return true;
2068 }
2069
2070 return false;
2071}
2072
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002073ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2074 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002075 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2076 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002077 //
2078 // This assumption is optimistic, as there could be free registers available
2079 // when we need to pass this argument in memory, and LLVM could try to pass
2080 // the argument in the free register. This does not seem to happen currently,
2081 // but this code would be much safer if we could mark the argument with
2082 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002083 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002084 // Treat an enum type as its underlying type.
2085 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2086 Ty = EnumTy->getDecl()->getIntegerType();
2087
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002088 return (Ty->isPromotableIntegerType() ?
2089 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002090 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002091
Mark Lacey3825e832013-10-06 01:33:34 +00002092 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002093 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002094
Chris Lattner44c2b902011-05-22 23:21:23 +00002095 // Compute the byval alignment. We specify the alignment of the byval in all
2096 // cases so that the mid-level optimizer knows the alignment of the byval.
2097 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002098
2099 // Attempt to avoid passing indirect results using byval when possible. This
2100 // is important for good codegen.
2101 //
2102 // We do this by coercing the value into a scalar type which the backend can
2103 // handle naturally (i.e., without using byval).
2104 //
2105 // For simplicity, we currently only do this when we have exhausted all of the
2106 // free integer registers. Doing this when there are free integer registers
2107 // would require more care, as we would have to ensure that the coerced value
2108 // did not claim the unused register. That would require either reording the
2109 // arguments to the function (so that any subsequent inreg values came first),
2110 // or only doing this optimization when there were no following arguments that
2111 // might be inreg.
2112 //
2113 // We currently expect it to be rare (particularly in well written code) for
2114 // arguments to be passed on the stack when there are still free integer
2115 // registers available (this would typically imply large structs being passed
2116 // by value), so this seems like a fair tradeoff for now.
2117 //
2118 // We can revisit this if the backend grows support for 'onstack' parameter
2119 // attributes. See PR12193.
2120 if (freeIntRegs == 0) {
2121 uint64_t Size = getContext().getTypeSize(Ty);
2122
2123 // If this type fits in an eightbyte, coerce it into the matching integral
2124 // type, which will end up on the stack (with alignment 8).
2125 if (Align == 8 && Size <= 64)
2126 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2127 Size));
2128 }
2129
Chris Lattner44c2b902011-05-22 23:21:23 +00002130 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002131}
2132
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002133/// GetByteVectorType - The ABI specifies that a value should be passed in an
2134/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002135/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002136llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002137 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002138
Chris Lattner9fa15c32010-07-29 05:02:29 +00002139 // Wrapper structs that just contain vectors are passed just like vectors,
2140 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002141 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002142 while (STy && STy->getNumElements() == 1) {
2143 IRType = STy->getElementType(0);
2144 STy = dyn_cast<llvm::StructType>(IRType);
2145 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002146
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002147 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002148 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2149 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002150 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002151 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002152 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2153 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2154 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2155 EltTy->isIntegerTy(128)))
2156 return VT;
2157 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002158
Chris Lattner4200fe42010-07-29 04:56:46 +00002159 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2160}
2161
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002162/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2163/// is known to either be off the end of the specified type or being in
2164/// alignment padding. The user type specified is known to be at most 128 bits
2165/// in size, and have passed through X86_64ABIInfo::classify with a successful
2166/// classification that put one of the two halves in the INTEGER class.
2167///
2168/// It is conservatively correct to return false.
2169static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2170 unsigned EndBit, ASTContext &Context) {
2171 // If the bytes being queried are off the end of the type, there is no user
2172 // data hiding here. This handles analysis of builtins, vectors and other
2173 // types that don't contain interesting padding.
2174 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2175 if (TySize <= StartBit)
2176 return true;
2177
Chris Lattner98076a22010-07-29 07:43:55 +00002178 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2179 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2180 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2181
2182 // Check each element to see if the element overlaps with the queried range.
2183 for (unsigned i = 0; i != NumElts; ++i) {
2184 // If the element is after the span we care about, then we're done..
2185 unsigned EltOffset = i*EltSize;
2186 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002187
Chris Lattner98076a22010-07-29 07:43:55 +00002188 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2189 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2190 EndBit-EltOffset, Context))
2191 return false;
2192 }
2193 // If it overlaps no elements, then it is safe to process as padding.
2194 return true;
2195 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002196
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002197 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2198 const RecordDecl *RD = RT->getDecl();
2199 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002200
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002201 // If this is a C++ record, check the bases first.
2202 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002203 for (const auto &I : CXXRD->bases()) {
2204 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002205 "Unexpected base class!");
2206 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002207 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002208
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002209 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002210 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002211 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002212
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002213 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002214 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002215 EndBit-BaseOffset, Context))
2216 return false;
2217 }
2218 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002219
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002220 // Verify that no field has data that overlaps the region of interest. Yes
2221 // this could be sped up a lot by being smarter about queried fields,
2222 // however we're only looking at structs up to 16 bytes, so we don't care
2223 // much.
2224 unsigned idx = 0;
2225 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2226 i != e; ++i, ++idx) {
2227 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002228
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002229 // If we found a field after the region we care about, then we're done.
2230 if (FieldOffset >= EndBit) break;
2231
2232 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2233 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2234 Context))
2235 return false;
2236 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002237
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002238 // If nothing in this record overlapped the area of interest, then we're
2239 // clean.
2240 return true;
2241 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002242
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002243 return false;
2244}
2245
Chris Lattnere556a712010-07-29 18:39:32 +00002246/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2247/// float member at the specified offset. For example, {int,{float}} has a
2248/// float at offset 4. It is conservatively correct for this routine to return
2249/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002250static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002251 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002252 // Base case if we find a float.
2253 if (IROffset == 0 && IRType->isFloatTy())
2254 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002255
Chris Lattnere556a712010-07-29 18:39:32 +00002256 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002257 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002258 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2259 unsigned Elt = SL->getElementContainingOffset(IROffset);
2260 IROffset -= SL->getElementOffset(Elt);
2261 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2262 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002263
Chris Lattnere556a712010-07-29 18:39:32 +00002264 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002265 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2266 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002267 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2268 IROffset -= IROffset/EltSize*EltSize;
2269 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2270 }
2271
2272 return false;
2273}
2274
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002275
2276/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2277/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002278llvm::Type *X86_64ABIInfo::
2279GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002280 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002281 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002282 // pass as float if the last 4 bytes is just padding. This happens for
2283 // structs that contain 3 floats.
2284 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2285 SourceOffset*8+64, getContext()))
2286 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002287
Chris Lattnere556a712010-07-29 18:39:32 +00002288 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2289 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2290 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002291 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2292 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002293 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002294
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002295 return llvm::Type::getDoubleTy(getVMContext());
2296}
2297
2298
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002299/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2300/// an 8-byte GPR. This means that we either have a scalar or we are talking
2301/// about the high or low part of an up-to-16-byte struct. This routine picks
2302/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002303/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2304/// etc).
2305///
2306/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2307/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2308/// the 8-byte value references. PrefType may be null.
2309///
Alp Toker9907f082014-07-09 14:06:35 +00002310/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002311/// an offset into this that we're processing (which is always either 0 or 8).
2312///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002313llvm::Type *X86_64ABIInfo::
2314GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002315 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002316 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2317 // returning an 8-byte unit starting with it. See if we can safely use it.
2318 if (IROffset == 0) {
2319 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002320 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2321 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002322 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002323
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002324 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2325 // goodness in the source type is just tail padding. This is allowed to
2326 // kick in for struct {double,int} on the int, but not on
2327 // struct{double,int,int} because we wouldn't return the second int. We
2328 // have to do this analysis on the source type because we can't depend on
2329 // unions being lowered a specific way etc.
2330 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002331 IRType->isIntegerTy(32) ||
2332 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2333 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2334 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002335
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002336 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2337 SourceOffset*8+64, getContext()))
2338 return IRType;
2339 }
2340 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002341
Chris Lattner2192fe52011-07-18 04:24:23 +00002342 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002343 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002344 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002345 if (IROffset < SL->getSizeInBytes()) {
2346 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2347 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002348
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002349 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2350 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002351 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002352 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002353
Chris Lattner2192fe52011-07-18 04:24:23 +00002354 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002355 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002356 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002357 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002358 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2359 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002360 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002361
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002362 // Okay, we don't have any better idea of what to pass, so we pass this in an
2363 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002364 unsigned TySizeInBytes =
2365 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002366
Chris Lattner3f763422010-07-29 17:34:39 +00002367 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002368
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002369 // It is always safe to classify this as an integer type up to i64 that
2370 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002371 return llvm::IntegerType::get(getVMContext(),
2372 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002373}
2374
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002375
2376/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2377/// be used as elements of a two register pair to pass or return, return a
2378/// first class aggregate to represent them. For example, if the low part of
2379/// a by-value argument should be passed as i32* and the high part as float,
2380/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002381static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002382GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002383 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002384 // In order to correctly satisfy the ABI, we need to the high part to start
2385 // at offset 8. If the high and low parts we inferred are both 4-byte types
2386 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2387 // the second element at offset 8. Check for this:
2388 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2389 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002390 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002391 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002392
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002393 // To handle this, we have to increase the size of the low part so that the
2394 // second element will start at an 8 byte offset. We can't increase the size
2395 // of the second element because it might make us access off the end of the
2396 // struct.
2397 if (HiStart != 8) {
2398 // There are only two sorts of types the ABI generation code can produce for
2399 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2400 // Promote these to a larger type.
2401 if (Lo->isFloatTy())
2402 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2403 else {
2404 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2405 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2406 }
2407 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002408
Chris Lattnera5f58b02011-07-09 17:41:47 +00002409 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002410
2411
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002412 // Verify that the second element is at an 8-byte offset.
2413 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2414 "Invalid x86-64 argument pair!");
2415 return Result;
2416}
2417
Chris Lattner31faff52010-07-28 23:06:14 +00002418ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002419classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002420 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2421 // classification algorithm.
2422 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002423 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002424
2425 // Check some invariants.
2426 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002427 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2428
Craig Topper8a13c412014-05-21 05:09:00 +00002429 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002430 switch (Lo) {
2431 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002432 if (Hi == NoClass)
2433 return ABIArgInfo::getIgnore();
2434 // If the low part is just padding, it takes no register, leave ResType
2435 // null.
2436 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2437 "Unknown missing lo part");
2438 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002439
2440 case SSEUp:
2441 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002442 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002443
2444 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2445 // hidden argument.
2446 case Memory:
2447 return getIndirectReturnResult(RetTy);
2448
2449 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2450 // available register of the sequence %rax, %rdx is used.
2451 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002452 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002453
Chris Lattner1f3a0632010-07-29 21:42:50 +00002454 // If we have a sign or zero extended integer, make sure to return Extend
2455 // so that the parameter gets the right LLVM IR attributes.
2456 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2457 // Treat an enum type as its underlying type.
2458 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2459 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002460
Chris Lattner1f3a0632010-07-29 21:42:50 +00002461 if (RetTy->isIntegralOrEnumerationType() &&
2462 RetTy->isPromotableIntegerType())
2463 return ABIArgInfo::getExtend();
2464 }
Chris Lattner31faff52010-07-28 23:06:14 +00002465 break;
2466
2467 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2468 // available SSE register of the sequence %xmm0, %xmm1 is used.
2469 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002470 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002471 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002472
2473 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2474 // returned on the X87 stack in %st0 as 80-bit x87 number.
2475 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002476 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002477 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002478
2479 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2480 // part of the value is returned in %st0 and the imaginary part in
2481 // %st1.
2482 case ComplexX87:
2483 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002484 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002485 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002486 NULL);
2487 break;
2488 }
2489
Craig Topper8a13c412014-05-21 05:09:00 +00002490 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002491 switch (Hi) {
2492 // Memory was handled previously and X87 should
2493 // never occur as a hi class.
2494 case Memory:
2495 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002496 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002497
2498 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002499 case NoClass:
2500 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002501
Chris Lattner52b3c132010-09-01 00:20:33 +00002502 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002503 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002504 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2505 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002506 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002507 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002508 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002509 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2510 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002511 break;
2512
2513 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002514 // is passed in the next available eightbyte chunk if the last used
2515 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002516 //
Chris Lattner57540c52011-04-15 05:22:18 +00002517 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002518 case SSEUp:
2519 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002520 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002521 break;
2522
2523 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2524 // returned together with the previous X87 value in %st0.
2525 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002526 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002527 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002528 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002529 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002530 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002531 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002532 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2533 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002534 }
Chris Lattner31faff52010-07-28 23:06:14 +00002535 break;
2536 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002537
Chris Lattner52b3c132010-09-01 00:20:33 +00002538 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002539 // known to pass in the high eightbyte of the result. We do this by forming a
2540 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002541 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002542 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002543
Chris Lattner1f3a0632010-07-29 21:42:50 +00002544 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002545}
2546
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002547ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002548 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2549 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002550 const
2551{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002552 Ty = useFirstFieldIfTransparentUnion(Ty);
2553
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002554 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002555 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002556
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557 // Check some invariants.
2558 // FIXME: Enforce these by construction.
2559 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2561
2562 neededInt = 0;
2563 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002564 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002565 switch (Lo) {
2566 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002567 if (Hi == NoClass)
2568 return ABIArgInfo::getIgnore();
2569 // If the low part is just padding, it takes no register, leave ResType
2570 // null.
2571 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2572 "Unknown missing lo part");
2573 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002574
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002575 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2576 // on the stack.
2577 case Memory:
2578
2579 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2580 // COMPLEX_X87, it is passed in memory.
2581 case X87:
2582 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002583 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002584 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002585 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002586
2587 case SSEUp:
2588 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002589 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002590
2591 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2592 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2593 // and %r9 is used.
2594 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002595 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002596
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002597 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002598 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002599
2600 // If we have a sign or zero extended integer, make sure to return Extend
2601 // so that the parameter gets the right LLVM IR attributes.
2602 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2603 // Treat an enum type as its underlying type.
2604 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2605 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002606
Chris Lattner1f3a0632010-07-29 21:42:50 +00002607 if (Ty->isIntegralOrEnumerationType() &&
2608 Ty->isPromotableIntegerType())
2609 return ABIArgInfo::getExtend();
2610 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002611
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002612 break;
2613
2614 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2615 // available SSE register is used, the registers are taken in the
2616 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002617 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002618 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002619 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002620 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 break;
2622 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002623 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002624
Craig Topper8a13c412014-05-21 05:09:00 +00002625 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626 switch (Hi) {
2627 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002628 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 // which is passed in memory.
2630 case Memory:
2631 case X87:
2632 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002633 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002634
2635 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002636
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002637 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002638 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002639 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002640 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002641
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002642 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2643 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002644 break;
2645
2646 // X87Up generally doesn't occur here (long double is passed in
2647 // memory), except in situations involving unions.
2648 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002649 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002650 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002651
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002652 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2653 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002654
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002655 ++neededSSE;
2656 break;
2657
2658 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2659 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002660 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002662 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002663 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002664 break;
2665 }
2666
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002667 // If a high part was specified, merge it together with the low part. It is
2668 // known to pass in the high eightbyte of the result. We do this by forming a
2669 // first class struct aggregate with the high and low part: {low, high}
2670 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002671 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002672
Chris Lattner1f3a0632010-07-29 21:42:50 +00002673 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674}
2675
Chris Lattner22326a12010-07-29 02:31:05 +00002676void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002677
Reid Kleckner40ca9132014-05-13 22:05:45 +00002678 if (!getCXXABI().classifyReturnType(FI))
2679 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680
2681 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002682 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683
2684 // If the return value is indirect, then the hidden argument is consuming one
2685 // integer register.
2686 if (FI.getReturnInfo().isIndirect())
2687 --freeIntRegs;
2688
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002689 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2691 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002692 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002694 it != ie; ++it, ++ArgNo) {
2695 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002696
Bill Wendling9987c0e2010-10-18 23:51:38 +00002697 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002698 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002699 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700
2701 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2702 // eightbyte of an argument, the whole argument is passed on the
2703 // stack. If registers have already been assigned for some
2704 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002705 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706 freeIntRegs -= neededInt;
2707 freeSSERegs -= neededSSE;
2708 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002709 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002710 }
2711 }
2712}
2713
2714static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2715 QualType Ty,
2716 CodeGenFunction &CGF) {
2717 llvm::Value *overflow_arg_area_p =
2718 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2719 llvm::Value *overflow_arg_area =
2720 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2721
2722 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2723 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002724 // It isn't stated explicitly in the standard, but in practice we use
2725 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002726 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2727 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002728 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002729 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002730 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002731 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2732 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002733 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002734 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 overflow_arg_area =
2736 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2737 overflow_arg_area->getType(),
2738 "overflow_arg_area.align");
2739 }
2740
2741 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002742 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002743 llvm::Value *Res =
2744 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002745 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002746
2747 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2748 // l->overflow_arg_area + sizeof(type).
2749 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2750 // an 8 byte boundary.
2751
2752 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002753 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002754 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002755 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2756 "overflow_arg_area.next");
2757 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2758
2759 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2760 return Res;
2761}
2762
2763llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2764 CodeGenFunction &CGF) const {
2765 // Assume that va_list type is correct; should be pointer to LLVM type:
2766 // struct {
2767 // i32 gp_offset;
2768 // i32 fp_offset;
2769 // i8* overflow_arg_area;
2770 // i8* reg_save_area;
2771 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002772 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002773
Chris Lattner9723d6c2010-03-11 18:19:55 +00002774 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002775 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2776 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002777
2778 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2779 // in the registers. If not go to step 7.
2780 if (!neededInt && !neededSSE)
2781 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2782
2783 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2784 // general purpose registers needed to pass type and num_fp to hold
2785 // the number of floating point registers needed.
2786
2787 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2788 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2789 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2790 //
2791 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2792 // register save space).
2793
Craig Topper8a13c412014-05-21 05:09:00 +00002794 llvm::Value *InRegs = nullptr;
2795 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2796 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002797 if (neededInt) {
2798 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2799 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002800 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2801 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002802 }
2803
2804 if (neededSSE) {
2805 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2806 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2807 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002808 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2809 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2811 }
2812
2813 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2814 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2815 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2816 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2817
2818 // Emit code to load the value if it was passed in registers.
2819
2820 CGF.EmitBlock(InRegBlock);
2821
2822 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2823 // an offset of l->gp_offset and/or l->fp_offset. This may require
2824 // copying to a temporary location in case the parameter is passed
2825 // in different register classes or requires an alignment greater
2826 // than 8 for general purpose registers and 16 for XMM registers.
2827 //
2828 // FIXME: This really results in shameful code when we end up needing to
2829 // collect arguments from different places; often what should result in a
2830 // simple assembling of a structure from scattered addresses has many more
2831 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002832 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002833 llvm::Value *RegAddr =
2834 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2835 "reg_save_area");
2836 if (neededInt && neededSSE) {
2837 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002838 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002839 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002840 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2841 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002842 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002843 llvm::Type *TyLo = ST->getElementType(0);
2844 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002845 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002846 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002847 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2848 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002849 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2850 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002851 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2852 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 llvm::Value *V =
2854 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2855 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2856 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2857 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2858
Owen Anderson170229f2009-07-14 23:10:40 +00002859 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002860 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002861 } else if (neededInt) {
2862 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2863 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002864 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002865
2866 // Copy to a temporary if necessary to ensure the appropriate alignment.
2867 std::pair<CharUnits, CharUnits> SizeAlign =
2868 CGF.getContext().getTypeInfoInChars(Ty);
2869 uint64_t TySize = SizeAlign.first.getQuantity();
2870 unsigned TyAlign = SizeAlign.second.getQuantity();
2871 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002872 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2873 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2874 RegAddr = Tmp;
2875 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002876 } else if (neededSSE == 1) {
2877 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2878 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2879 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002880 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002881 assert(neededSSE == 2 && "Invalid number of needed registers!");
2882 // SSE registers are spaced 16 bytes apart in the register save
2883 // area, we need to collect the two eightbytes together.
2884 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002885 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002886 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002887 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002888 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002889 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2890 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2891 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002892 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2893 DblPtrTy));
2894 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2895 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2896 DblPtrTy));
2897 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2898 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2899 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002900 }
2901
2902 // AMD64-ABI 3.5.7p5: Step 5. Set:
2903 // l->gp_offset = l->gp_offset + num_gp * 8
2904 // l->fp_offset = l->fp_offset + num_fp * 16.
2905 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002906 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2908 gp_offset_p);
2909 }
2910 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002911 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002912 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2913 fp_offset_p);
2914 }
2915 CGF.EmitBranch(ContBlock);
2916
2917 // Emit code to load the value if it was passed in memory.
2918
2919 CGF.EmitBlock(InMemBlock);
2920 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2921
2922 // Return the appropriate result.
2923
2924 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002925 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002926 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002927 ResAddr->addIncoming(RegAddr, InRegBlock);
2928 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002929 return ResAddr;
2930}
2931
Reid Kleckner80944df2014-10-31 22:00:51 +00002932ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2933 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002934
2935 if (Ty->isVoidType())
2936 return ABIArgInfo::getIgnore();
2937
2938 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2939 Ty = EnumTy->getDecl()->getIntegerType();
2940
Reid Kleckner80944df2014-10-31 22:00:51 +00002941 TypeInfo Info = getContext().getTypeInfo(Ty);
2942 uint64_t Width = Info.Width;
2943 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002944
Reid Kleckner9005f412014-05-02 00:51:20 +00002945 const RecordType *RT = Ty->getAs<RecordType>();
2946 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002947 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002948 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002949 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2950 }
2951
2952 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002953 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2954
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002955 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00002956 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002957 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00002958 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00002959 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002960
Reid Kleckner80944df2014-10-31 22:00:51 +00002961 // vectorcall adds the concept of a homogenous vector aggregate, similar to
2962 // other targets.
2963 const Type *Base = nullptr;
2964 uint64_t NumElts = 0;
2965 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
2966 if (FreeSSERegs >= NumElts) {
2967 FreeSSERegs -= NumElts;
2968 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
2969 return ABIArgInfo::getDirect();
2970 return ABIArgInfo::getExpand();
2971 }
2972 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
2973 }
2974
2975
Reid Klecknerec87fec2014-05-02 01:17:12 +00002976 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002977 // If the member pointer is represented by an LLVM int or ptr, pass it
2978 // directly.
2979 llvm::Type *LLTy = CGT.ConvertType(Ty);
2980 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2981 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002982 }
2983
2984 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002985 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2986 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00002987 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00002988 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002989
Reid Kleckner9005f412014-05-02 00:51:20 +00002990 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00002991 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002992 }
2993
Julien Lerouge10dcff82014-08-27 00:36:55 +00002994 // Bool type is always extended to the ABI, other builtin types are not
2995 // extended.
2996 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2997 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002998 return ABIArgInfo::getExtend();
2999
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003000 return ABIArgInfo::getDirect();
3001}
3002
3003void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003004 bool IsVectorCall =
3005 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003006
Reid Kleckner80944df2014-10-31 22:00:51 +00003007 // We can use up to 4 SSE return registers with vectorcall.
3008 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3009 if (!getCXXABI().classifyReturnType(FI))
3010 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3011
3012 // We can use up to 6 SSE register parameters with vectorcall.
3013 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003014 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003015 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003016}
3017
Chris Lattner04dc9572010-08-31 16:44:54 +00003018llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3019 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003020 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003021
Chris Lattner04dc9572010-08-31 16:44:54 +00003022 CGBuilderTy &Builder = CGF.Builder;
3023 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3024 "ap");
3025 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3026 llvm::Type *PTy =
3027 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3028 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3029
3030 uint64_t Offset =
3031 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3032 llvm::Value *NextAddr =
3033 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3034 "ap.next");
3035 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3036
3037 return AddrTyped;
3038}
Chris Lattner0cf24192010-06-28 20:05:43 +00003039
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003040namespace {
3041
Derek Schuffa2020962012-10-16 22:30:41 +00003042class NaClX86_64ABIInfo : public ABIInfo {
3043 public:
3044 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3045 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00003046 void computeInfo(CGFunctionInfo &FI) const override;
3047 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3048 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00003049 private:
3050 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3051 X86_64ABIInfo NInfo; // Used for everything else.
3052};
3053
3054class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00003055 bool HasAVX;
Derek Schuffa2020962012-10-16 22:30:41 +00003056 public:
Alexander Musman09184fe2014-09-30 05:29:28 +00003057 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3058 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
3059 }
3060 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3061 return HasAVX ? 32 : 16;
3062 }
Derek Schuffa2020962012-10-16 22:30:41 +00003063};
3064
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003065}
3066
Derek Schuffa2020962012-10-16 22:30:41 +00003067void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3068 if (FI.getASTCallingConvention() == CC_PnaclCall)
3069 PInfo.computeInfo(FI);
3070 else
3071 NInfo.computeInfo(FI);
3072}
3073
3074llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3075 CodeGenFunction &CGF) const {
3076 // Always use the native convention; calling pnacl-style varargs functions
3077 // is unuspported.
3078 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
3079}
3080
3081
John McCallea8d8bb2010-03-11 00:10:12 +00003082// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003083namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003084/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3085class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003086public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003087 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3088
3089 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3090 CodeGenFunction &CGF) const override;
3091};
3092
3093class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3094public:
3095 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003096
Craig Topper4f12f102014-03-12 06:41:41 +00003097 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003098 // This is recovered from gcc output.
3099 return 1; // r1 is the dedicated stack pointer
3100 }
3101
3102 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003103 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003104
3105 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3106 return 16; // Natural alignment for Altivec vectors.
3107 }
John McCallea8d8bb2010-03-11 00:10:12 +00003108};
3109
3110}
3111
Roman Divacky8a12d842014-11-03 18:32:54 +00003112llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3113 QualType Ty,
3114 CodeGenFunction &CGF) const {
3115 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3116 // TODO: Implement this. For now ignore.
3117 (void)CTy;
3118 return nullptr;
3119 }
3120
3121 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3122 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3123 llvm::Type *CharPtr = CGF.Int8PtrTy;
3124 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3125
3126 CGBuilderTy &Builder = CGF.Builder;
3127 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3128 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3129 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3130 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3131 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3132 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3133 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3134 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3135 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3136 // Align GPR when TY is i64.
3137 if (isI64) {
3138 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3139 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3140 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3141 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3142 }
3143 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3144 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3145 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3146 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3147 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3148
3149 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3150 Builder.getInt8(8), "cond");
3151
3152 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3153 Builder.getInt8(isInt ? 4 : 8));
3154
3155 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3156
3157 if (Ty->isFloatingType())
3158 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3159
3160 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3161 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3162 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3163
3164 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3165
3166 CGF.EmitBlock(UsingRegs);
3167
3168 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3169 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3170 // Increase the GPR/FPR indexes.
3171 if (isInt) {
3172 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3173 Builder.CreateStore(GPR, GPRPtr);
3174 } else {
3175 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3176 Builder.CreateStore(FPR, FPRPtr);
3177 }
3178 CGF.EmitBranch(Cont);
3179
3180 CGF.EmitBlock(UsingOverflow);
3181
3182 // Increase the overflow area.
3183 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3184 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3185 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3186 CGF.EmitBranch(Cont);
3187
3188 CGF.EmitBlock(Cont);
3189
3190 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3191 Result->addIncoming(Result1, UsingRegs);
3192 Result->addIncoming(Result2, UsingOverflow);
3193
3194 if (Ty->isAggregateType()) {
3195 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3196 return Builder.CreateLoad(AGGPtr, false, "aggr");
3197 }
3198
3199 return Result;
3200}
3201
John McCallea8d8bb2010-03-11 00:10:12 +00003202bool
3203PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3204 llvm::Value *Address) const {
3205 // This is calculated from the LLVM and GCC tables and verified
3206 // against gcc output. AFAIK all ABIs use the same encoding.
3207
3208 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003209
Chris Lattnerece04092012-02-07 00:39:47 +00003210 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003211 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3212 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3213 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3214
3215 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003216 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003217
3218 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003219 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003220
3221 // 64-76 are various 4-byte special-purpose registers:
3222 // 64: mq
3223 // 65: lr
3224 // 66: ctr
3225 // 67: ap
3226 // 68-75 cr0-7
3227 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003228 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003229
3230 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003231 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003232
3233 // 109: vrsave
3234 // 110: vscr
3235 // 111: spe_acc
3236 // 112: spefscr
3237 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003238 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003239
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003240 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003241}
3242
Roman Divackyd966e722012-05-09 18:22:46 +00003243// PowerPC-64
3244
3245namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003246/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3247class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003248public:
3249 enum ABIKind {
3250 ELFv1 = 0,
3251 ELFv2
3252 };
3253
3254private:
3255 static const unsigned GPRBits = 64;
3256 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003257
3258public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003259 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3260 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003261
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003262 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003263 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003264
3265 ABIArgInfo classifyReturnType(QualType RetTy) const;
3266 ABIArgInfo classifyArgumentType(QualType Ty) const;
3267
Reid Klecknere9f6a712014-10-31 17:10:41 +00003268 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3269 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3270 uint64_t Members) const override;
3271
Bill Schmidt84d37792012-10-12 19:26:17 +00003272 // TODO: We can add more logic to computeInfo to improve performance.
3273 // Example: For aggregate arguments that fit in a register, we could
3274 // use getDirectInReg (as is done below for structs containing a single
3275 // floating-point value) to avoid pushing them to memory on function
3276 // entry. This would require changing the logic in PPCISelLowering
3277 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003278 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003279 if (!getCXXABI().classifyReturnType(FI))
3280 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003281 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003282 // We rely on the default argument classification for the most part.
3283 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003284 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003285 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003286 if (T) {
3287 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003288 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3289 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003290 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003291 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003292 continue;
3293 }
3294 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003295 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003296 }
3297 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003298
Craig Topper4f12f102014-03-12 06:41:41 +00003299 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3300 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003301};
3302
3303class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3304public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003305 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3306 PPC64_SVR4_ABIInfo::ABIKind Kind)
3307 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003308
Craig Topper4f12f102014-03-12 06:41:41 +00003309 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003310 // This is recovered from gcc output.
3311 return 1; // r1 is the dedicated stack pointer
3312 }
3313
3314 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003315 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003316
3317 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3318 return 16; // Natural alignment for Altivec and VSX vectors.
3319 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003320};
3321
Roman Divackyd966e722012-05-09 18:22:46 +00003322class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3323public:
3324 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3325
Craig Topper4f12f102014-03-12 06:41:41 +00003326 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003327 // This is recovered from gcc output.
3328 return 1; // r1 is the dedicated stack pointer
3329 }
3330
3331 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003332 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003333
3334 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3335 return 16; // Natural alignment for Altivec vectors.
3336 }
Roman Divackyd966e722012-05-09 18:22:46 +00003337};
3338
3339}
3340
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003341// Return true if the ABI requires Ty to be passed sign- or zero-
3342// extended to 64 bits.
3343bool
3344PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3345 // Treat an enum type as its underlying type.
3346 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3347 Ty = EnumTy->getDecl()->getIntegerType();
3348
3349 // Promotable integer types are required to be promoted by the ABI.
3350 if (Ty->isPromotableIntegerType())
3351 return true;
3352
3353 // In addition to the usual promotable integer types, we also need to
3354 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3355 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3356 switch (BT->getKind()) {
3357 case BuiltinType::Int:
3358 case BuiltinType::UInt:
3359 return true;
3360 default:
3361 break;
3362 }
3363
3364 return false;
3365}
3366
Ulrich Weigand581badc2014-07-10 17:20:07 +00003367/// isAlignedParamType - Determine whether a type requires 16-byte
3368/// alignment in the parameter area.
3369bool
3370PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3371 // Complex types are passed just like their elements.
3372 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3373 Ty = CTy->getElementType();
3374
3375 // Only vector types of size 16 bytes need alignment (larger types are
3376 // passed via reference, smaller types are not aligned).
3377 if (Ty->isVectorType())
3378 return getContext().getTypeSize(Ty) == 128;
3379
3380 // For single-element float/vector structs, we consider the whole type
3381 // to have the same alignment requirements as its single element.
3382 const Type *AlignAsType = nullptr;
3383 const Type *EltType = isSingleElementStruct(Ty, getContext());
3384 if (EltType) {
3385 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3386 if ((EltType->isVectorType() &&
3387 getContext().getTypeSize(EltType) == 128) ||
3388 (BT && BT->isFloatingPoint()))
3389 AlignAsType = EltType;
3390 }
3391
Ulrich Weigandb7122372014-07-21 00:48:09 +00003392 // Likewise for ELFv2 homogeneous aggregates.
3393 const Type *Base = nullptr;
3394 uint64_t Members = 0;
3395 if (!AlignAsType && Kind == ELFv2 &&
3396 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3397 AlignAsType = Base;
3398
Ulrich Weigand581badc2014-07-10 17:20:07 +00003399 // With special case aggregates, only vector base types need alignment.
3400 if (AlignAsType)
3401 return AlignAsType->isVectorType();
3402
3403 // Otherwise, we only need alignment for any aggregate type that
3404 // has an alignment requirement of >= 16 bytes.
3405 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3406 return true;
3407
3408 return false;
3409}
3410
Ulrich Weigandb7122372014-07-21 00:48:09 +00003411/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3412/// aggregate. Base is set to the base element type, and Members is set
3413/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003414bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3415 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003416 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3417 uint64_t NElements = AT->getSize().getZExtValue();
3418 if (NElements == 0)
3419 return false;
3420 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3421 return false;
3422 Members *= NElements;
3423 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3424 const RecordDecl *RD = RT->getDecl();
3425 if (RD->hasFlexibleArrayMember())
3426 return false;
3427
3428 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003429
3430 // If this is a C++ record, check the bases first.
3431 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3432 for (const auto &I : CXXRD->bases()) {
3433 // Ignore empty records.
3434 if (isEmptyRecord(getContext(), I.getType(), true))
3435 continue;
3436
3437 uint64_t FldMembers;
3438 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3439 return false;
3440
3441 Members += FldMembers;
3442 }
3443 }
3444
Ulrich Weigandb7122372014-07-21 00:48:09 +00003445 for (const auto *FD : RD->fields()) {
3446 // Ignore (non-zero arrays of) empty records.
3447 QualType FT = FD->getType();
3448 while (const ConstantArrayType *AT =
3449 getContext().getAsConstantArrayType(FT)) {
3450 if (AT->getSize().getZExtValue() == 0)
3451 return false;
3452 FT = AT->getElementType();
3453 }
3454 if (isEmptyRecord(getContext(), FT, true))
3455 continue;
3456
3457 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3458 if (getContext().getLangOpts().CPlusPlus &&
3459 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3460 continue;
3461
3462 uint64_t FldMembers;
3463 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3464 return false;
3465
3466 Members = (RD->isUnion() ?
3467 std::max(Members, FldMembers) : Members + FldMembers);
3468 }
3469
3470 if (!Base)
3471 return false;
3472
3473 // Ensure there is no padding.
3474 if (getContext().getTypeSize(Base) * Members !=
3475 getContext().getTypeSize(Ty))
3476 return false;
3477 } else {
3478 Members = 1;
3479 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3480 Members = 2;
3481 Ty = CT->getElementType();
3482 }
3483
Reid Klecknere9f6a712014-10-31 17:10:41 +00003484 // Most ABIs only support float, double, and some vector type widths.
3485 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003486 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003487
3488 // The base type must be the same for all members. Types that
3489 // agree in both total size and mode (float vs. vector) are
3490 // treated as being equivalent here.
3491 const Type *TyPtr = Ty.getTypePtr();
3492 if (!Base)
3493 Base = TyPtr;
3494
3495 if (Base->isVectorType() != TyPtr->isVectorType() ||
3496 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3497 return false;
3498 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003499 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3500}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003501
Reid Klecknere9f6a712014-10-31 17:10:41 +00003502bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3503 // Homogeneous aggregates for ELFv2 must have base types of float,
3504 // double, long double, or 128-bit vectors.
3505 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3506 if (BT->getKind() == BuiltinType::Float ||
3507 BT->getKind() == BuiltinType::Double ||
3508 BT->getKind() == BuiltinType::LongDouble)
3509 return true;
3510 }
3511 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3512 if (getContext().getTypeSize(VT) == 128)
3513 return true;
3514 }
3515 return false;
3516}
3517
3518bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3519 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003520 // Vector types require one register, floating point types require one
3521 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003522 uint32_t NumRegs =
3523 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003524
3525 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003526 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003527}
3528
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003529ABIArgInfo
3530PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003531 Ty = useFirstFieldIfTransparentUnion(Ty);
3532
Bill Schmidt90b22c92012-11-27 02:46:43 +00003533 if (Ty->isAnyComplexType())
3534 return ABIArgInfo::getDirect();
3535
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003536 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3537 // or via reference (larger than 16 bytes).
3538 if (Ty->isVectorType()) {
3539 uint64_t Size = getContext().getTypeSize(Ty);
3540 if (Size > 128)
3541 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3542 else if (Size < 128) {
3543 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3544 return ABIArgInfo::getDirect(CoerceTy);
3545 }
3546 }
3547
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003548 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003549 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003550 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003551
Ulrich Weigand581badc2014-07-10 17:20:07 +00003552 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3553 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003554
3555 // ELFv2 homogeneous aggregates are passed as array types.
3556 const Type *Base = nullptr;
3557 uint64_t Members = 0;
3558 if (Kind == ELFv2 &&
3559 isHomogeneousAggregate(Ty, Base, Members)) {
3560 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3561 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3562 return ABIArgInfo::getDirect(CoerceTy);
3563 }
3564
Ulrich Weigand601957f2014-07-21 00:56:36 +00003565 // If an aggregate may end up fully in registers, we do not
3566 // use the ByVal method, but pass the aggregate as array.
3567 // This is usually beneficial since we avoid forcing the
3568 // back-end to store the argument to memory.
3569 uint64_t Bits = getContext().getTypeSize(Ty);
3570 if (Bits > 0 && Bits <= 8 * GPRBits) {
3571 llvm::Type *CoerceTy;
3572
3573 // Types up to 8 bytes are passed as integer type (which will be
3574 // properly aligned in the argument save area doubleword).
3575 if (Bits <= GPRBits)
3576 CoerceTy = llvm::IntegerType::get(getVMContext(),
3577 llvm::RoundUpToAlignment(Bits, 8));
3578 // Larger types are passed as arrays, with the base type selected
3579 // according to the required alignment in the save area.
3580 else {
3581 uint64_t RegBits = ABIAlign * 8;
3582 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3583 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3584 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3585 }
3586
3587 return ABIArgInfo::getDirect(CoerceTy);
3588 }
3589
Ulrich Weigandb7122372014-07-21 00:48:09 +00003590 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003591 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3592 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003593 }
3594
3595 return (isPromotableTypeForABI(Ty) ?
3596 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3597}
3598
3599ABIArgInfo
3600PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3601 if (RetTy->isVoidType())
3602 return ABIArgInfo::getIgnore();
3603
Bill Schmidta3d121c2012-12-17 04:20:17 +00003604 if (RetTy->isAnyComplexType())
3605 return ABIArgInfo::getDirect();
3606
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003607 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3608 // or via reference (larger than 16 bytes).
3609 if (RetTy->isVectorType()) {
3610 uint64_t Size = getContext().getTypeSize(RetTy);
3611 if (Size > 128)
3612 return ABIArgInfo::getIndirect(0);
3613 else if (Size < 128) {
3614 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3615 return ABIArgInfo::getDirect(CoerceTy);
3616 }
3617 }
3618
Ulrich Weigandb7122372014-07-21 00:48:09 +00003619 if (isAggregateTypeForABI(RetTy)) {
3620 // ELFv2 homogeneous aggregates are returned as array types.
3621 const Type *Base = nullptr;
3622 uint64_t Members = 0;
3623 if (Kind == ELFv2 &&
3624 isHomogeneousAggregate(RetTy, Base, Members)) {
3625 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3626 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3627 return ABIArgInfo::getDirect(CoerceTy);
3628 }
3629
3630 // ELFv2 small aggregates are returned in up to two registers.
3631 uint64_t Bits = getContext().getTypeSize(RetTy);
3632 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3633 if (Bits == 0)
3634 return ABIArgInfo::getIgnore();
3635
3636 llvm::Type *CoerceTy;
3637 if (Bits > GPRBits) {
3638 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3639 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3640 } else
3641 CoerceTy = llvm::IntegerType::get(getVMContext(),
3642 llvm::RoundUpToAlignment(Bits, 8));
3643 return ABIArgInfo::getDirect(CoerceTy);
3644 }
3645
3646 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003647 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003648 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003649
3650 return (isPromotableTypeForABI(RetTy) ?
3651 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3652}
3653
Bill Schmidt25cb3492012-10-03 19:18:57 +00003654// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3655llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3656 QualType Ty,
3657 CodeGenFunction &CGF) const {
3658 llvm::Type *BP = CGF.Int8PtrTy;
3659 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3660
3661 CGBuilderTy &Builder = CGF.Builder;
3662 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3663 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3664
Ulrich Weigand581badc2014-07-10 17:20:07 +00003665 // Handle types that require 16-byte alignment in the parameter save area.
3666 if (isAlignedParamType(Ty)) {
3667 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3668 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3669 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3670 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3671 }
3672
Bill Schmidt924c4782013-01-14 17:45:36 +00003673 // Update the va_list pointer. The pointer should be bumped by the
3674 // size of the object. We can trust getTypeSize() except for a complex
3675 // type whose base type is smaller than a doubleword. For these, the
3676 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003677 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003678 QualType BaseTy;
3679 unsigned CplxBaseSize = 0;
3680
3681 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3682 BaseTy = CTy->getElementType();
3683 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3684 if (CplxBaseSize < 8)
3685 SizeInBytes = 16;
3686 }
3687
Bill Schmidt25cb3492012-10-03 19:18:57 +00003688 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3689 llvm::Value *NextAddr =
3690 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3691 "ap.next");
3692 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3693
Bill Schmidt924c4782013-01-14 17:45:36 +00003694 // If we have a complex type and the base type is smaller than 8 bytes,
3695 // the ABI calls for the real and imaginary parts to be right-adjusted
3696 // in separate doublewords. However, Clang expects us to produce a
3697 // pointer to a structure with the two parts packed tightly. So generate
3698 // loads of the real and imaginary parts relative to the va_list pointer,
3699 // and store them to a temporary structure.
3700 if (CplxBaseSize && CplxBaseSize < 8) {
3701 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3702 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003703 if (CGF.CGM.getDataLayout().isBigEndian()) {
3704 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3705 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3706 } else {
3707 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3708 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003709 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3710 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3711 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3712 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3713 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3714 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3715 "vacplx");
3716 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3717 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3718 Builder.CreateStore(Real, RealPtr, false);
3719 Builder.CreateStore(Imag, ImagPtr, false);
3720 return Ptr;
3721 }
3722
Bill Schmidt25cb3492012-10-03 19:18:57 +00003723 // If the argument is smaller than 8 bytes, it is right-adjusted in
3724 // its doubleword slot. Adjust the pointer to pick it up from the
3725 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003726 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003727 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3728 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3729 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3730 }
3731
3732 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3733 return Builder.CreateBitCast(Addr, PTy);
3734}
3735
3736static bool
3737PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3738 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003739 // This is calculated from the LLVM and GCC tables and verified
3740 // against gcc output. AFAIK all ABIs use the same encoding.
3741
3742 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3743
3744 llvm::IntegerType *i8 = CGF.Int8Ty;
3745 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3746 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3747 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3748
3749 // 0-31: r0-31, the 8-byte general-purpose registers
3750 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3751
3752 // 32-63: fp0-31, the 8-byte floating-point registers
3753 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3754
3755 // 64-76 are various 4-byte special-purpose registers:
3756 // 64: mq
3757 // 65: lr
3758 // 66: ctr
3759 // 67: ap
3760 // 68-75 cr0-7
3761 // 76: xer
3762 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3763
3764 // 77-108: v0-31, the 16-byte vector registers
3765 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3766
3767 // 109: vrsave
3768 // 110: vscr
3769 // 111: spe_acc
3770 // 112: spefscr
3771 // 113: sfp
3772 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3773
3774 return false;
3775}
John McCallea8d8bb2010-03-11 00:10:12 +00003776
Bill Schmidt25cb3492012-10-03 19:18:57 +00003777bool
3778PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3779 CodeGen::CodeGenFunction &CGF,
3780 llvm::Value *Address) const {
3781
3782 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3783}
3784
3785bool
3786PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3787 llvm::Value *Address) const {
3788
3789 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3790}
3791
Chris Lattner0cf24192010-06-28 20:05:43 +00003792//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003793// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003794//===----------------------------------------------------------------------===//
3795
3796namespace {
3797
Tim Northover573cbee2014-05-24 12:52:07 +00003798class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003799public:
3800 enum ABIKind {
3801 AAPCS = 0,
3802 DarwinPCS
3803 };
3804
3805private:
3806 ABIKind Kind;
3807
3808public:
Tim Northover573cbee2014-05-24 12:52:07 +00003809 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003810
3811private:
3812 ABIKind getABIKind() const { return Kind; }
3813 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3814
3815 ABIArgInfo classifyReturnType(QualType RetTy) const;
3816 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3817 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003818 bool &IsSmallAggr, bool IsNamedArg) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003819 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3820 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3821 uint64_t Members) const override;
3822
Tim Northovera2ee4332014-03-29 15:09:45 +00003823 bool isIllegalVectorType(QualType Ty) const;
3824
David Blaikie1cbb9712014-11-14 19:09:44 +00003825 void computeInfo(CGFunctionInfo &FI) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003826 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3827 // number of SIMD and Floating-point registers allocated so far.
3828 // If the argument is an HFA or an HVA and there are sufficient unallocated
3829 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3830 // and Floating-point Registers (with one register per member of the HFA or
3831 // HVA). Otherwise, the NSRN is set to 8.
3832 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003833
Tim Northovera2ee4332014-03-29 15:09:45 +00003834 // To correctly handle small aggregates, we need to keep track of the number
3835 // of GPRs allocated so far. If the small aggregate can't all fit into
3836 // registers, it will be on stack. We don't allow the aggregate to be
3837 // partially in registers.
3838 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003839
3840 // Find the number of named arguments. Variadic arguments get special
3841 // treatment with the Darwin ABI.
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003842 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Bob Wilson373af732014-04-21 01:23:39 +00003843
Reid Kleckner40ca9132014-05-13 22:05:45 +00003844 if (!getCXXABI().classifyReturnType(FI))
3845 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003846 unsigned ArgNo = 0;
Tim Northovera2ee4332014-03-29 15:09:45 +00003847 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003848 it != ie; ++it, ++ArgNo) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003849 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3850 bool IsHA = false, IsSmallAggr = false;
3851 const unsigned NumVFPs = 8;
3852 const unsigned NumGPRs = 8;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003853 bool IsNamedArg = ArgNo < NumRequiredArgs;
Tim Northovera2ee4332014-03-29 15:09:45 +00003854 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003855 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003856
3857 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3858 // as sequences of floats since they'll get "holes" inserted as
3859 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003860 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3861 getContext().getTypeAlign(it->type) < 64) {
3862 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3863 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003864
Tim Northover07f16242014-04-18 10:47:44 +00003865 llvm::Type *CoerceTy = llvm::ArrayType::get(
3866 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3867 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003868 }
3869
Tim Northovera2ee4332014-03-29 15:09:45 +00003870 // If we do not have enough VFP registers for the HA, any VFP registers
3871 // that are unallocated are marked as unavailable. To achieve this, we add
3872 // padding of (NumVFPs - PreAllocation) floats.
3873 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3874 llvm::Type *PaddingTy = llvm::ArrayType::get(
3875 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003876 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003877 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003878
Tim Northovera2ee4332014-03-29 15:09:45 +00003879 // If we do not have enough GPRs for the small aggregate, any GPR regs
3880 // that are unallocated are marked as unavailable.
3881 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3882 llvm::Type *PaddingTy = llvm::ArrayType::get(
3883 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3884 it->info =
3885 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3886 }
3887 }
3888 }
3889
3890 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3891 CodeGenFunction &CGF) const;
3892
3893 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3894 CodeGenFunction &CGF) const;
3895
3896 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003897 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003898 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3899 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3900 }
3901};
3902
Tim Northover573cbee2014-05-24 12:52:07 +00003903class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003904public:
Tim Northover573cbee2014-05-24 12:52:07 +00003905 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3906 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003907
3908 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3909 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3910 }
3911
3912 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3913
3914 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3915};
3916}
3917
Tim Northover573cbee2014-05-24 12:52:07 +00003918ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3919 unsigned &AllocatedVFP,
3920 bool &IsHA,
3921 unsigned &AllocatedGPR,
3922 bool &IsSmallAggr,
3923 bool IsNamedArg) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003924 Ty = useFirstFieldIfTransparentUnion(Ty);
3925
Tim Northovera2ee4332014-03-29 15:09:45 +00003926 // Handle illegal vector types here.
3927 if (isIllegalVectorType(Ty)) {
3928 uint64_t Size = getContext().getTypeSize(Ty);
3929 if (Size <= 32) {
3930 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3931 AllocatedGPR++;
3932 return ABIArgInfo::getDirect(ResType);
3933 }
3934 if (Size == 64) {
3935 llvm::Type *ResType =
3936 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3937 AllocatedVFP++;
3938 return ABIArgInfo::getDirect(ResType);
3939 }
3940 if (Size == 128) {
3941 llvm::Type *ResType =
3942 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3943 AllocatedVFP++;
3944 return ABIArgInfo::getDirect(ResType);
3945 }
3946 AllocatedGPR++;
3947 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3948 }
3949 if (Ty->isVectorType())
3950 // Size of a legal vector should be either 64 or 128.
3951 AllocatedVFP++;
3952 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3953 if (BT->getKind() == BuiltinType::Half ||
3954 BT->getKind() == BuiltinType::Float ||
3955 BT->getKind() == BuiltinType::Double ||
3956 BT->getKind() == BuiltinType::LongDouble)
3957 AllocatedVFP++;
3958 }
3959
3960 if (!isAggregateTypeForABI(Ty)) {
3961 // Treat an enum type as its underlying type.
3962 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3963 Ty = EnumTy->getDecl()->getIntegerType();
3964
3965 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003966 unsigned Alignment = getContext().getTypeAlign(Ty);
3967 if (!isDarwinPCS() && Alignment > 64)
3968 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3969
Tim Northovera2ee4332014-03-29 15:09:45 +00003970 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3971 AllocatedGPR += RegsNeeded;
3972 }
3973 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3974 ? ABIArgInfo::getExtend()
3975 : ABIArgInfo::getDirect());
3976 }
3977
3978 // Structures with either a non-trivial destructor or a non-trivial
3979 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003980 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003981 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003982 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3983 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003984 }
3985
3986 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3987 // elsewhere for GNU compatibility.
3988 if (isEmptyRecord(getContext(), Ty, true)) {
3989 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3990 return ABIArgInfo::getIgnore();
3991
3992 ++AllocatedGPR;
3993 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3994 }
3995
3996 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003997 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003998 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003999 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004000 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00004001 if (!IsNamedArg && isDarwinPCS()) {
4002 // With the Darwin ABI, variadic arguments are always passed on the stack
4003 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
4004 uint64_t Size = getContext().getTypeSize(Ty);
4005 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
4006 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4007 }
4008 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00004009 return ABIArgInfo::getExpand();
4010 }
4011
4012 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4013 uint64_t Size = getContext().getTypeSize(Ty);
4014 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004015 unsigned Alignment = getContext().getTypeAlign(Ty);
4016 if (!isDarwinPCS() && Alignment > 64)
4017 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
4018
Tim Northovera2ee4332014-03-29 15:09:45 +00004019 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4020 AllocatedGPR += Size / 64;
4021 IsSmallAggr = true;
4022 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4023 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004024 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004025 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4026 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4027 }
4028 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4029 }
4030
4031 AllocatedGPR++;
4032 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4033}
4034
Tim Northover573cbee2014-05-24 12:52:07 +00004035ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004036 if (RetTy->isVoidType())
4037 return ABIArgInfo::getIgnore();
4038
4039 // Large vector types should be returned via memory.
4040 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4041 return ABIArgInfo::getIndirect(0);
4042
4043 if (!isAggregateTypeForABI(RetTy)) {
4044 // Treat an enum type as its underlying type.
4045 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4046 RetTy = EnumTy->getDecl()->getIntegerType();
4047
Tim Northover4dab6982014-04-18 13:46:08 +00004048 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4049 ? ABIArgInfo::getExtend()
4050 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004051 }
4052
Tim Northovera2ee4332014-03-29 15:09:45 +00004053 if (isEmptyRecord(getContext(), RetTy, true))
4054 return ABIArgInfo::getIgnore();
4055
Craig Topper8a13c412014-05-21 05:09:00 +00004056 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004057 uint64_t Members = 0;
4058 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004059 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4060 return ABIArgInfo::getDirect();
4061
4062 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4063 uint64_t Size = getContext().getTypeSize(RetTy);
4064 if (Size <= 128) {
4065 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4066 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4067 }
4068
4069 return ABIArgInfo::getIndirect(0);
4070}
4071
Tim Northover573cbee2014-05-24 12:52:07 +00004072/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4073bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004074 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4075 // Check whether VT is legal.
4076 unsigned NumElements = VT->getNumElements();
4077 uint64_t Size = getContext().getTypeSize(VT);
4078 // NumElements should be power of 2 between 1 and 16.
4079 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4080 return true;
4081 return Size != 64 && (Size != 128 || NumElements == 1);
4082 }
4083 return false;
4084}
4085
Reid Klecknere9f6a712014-10-31 17:10:41 +00004086bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4087 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4088 // point type or a short-vector type. This is the same as the 32-bit ABI,
4089 // but with the difference that any floating-point type is allowed,
4090 // including __fp16.
4091 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4092 if (BT->isFloatingPoint())
4093 return true;
4094 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4095 unsigned VecSize = getContext().getTypeSize(VT);
4096 if (VecSize == 64 || VecSize == 128)
4097 return true;
4098 }
4099 return false;
4100}
4101
4102bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4103 uint64_t Members) const {
4104 return Members <= 4;
4105}
4106
4107llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
4108 CodeGenFunction &CGF) const {
4109 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4110 bool IsHA = false, IsSmallAggr = false;
4111 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4112 IsSmallAggr, false /*IsNamedArg*/);
4113 bool IsIndirect = AI.isIndirect();
4114
Tim Northovera2ee4332014-03-29 15:09:45 +00004115 // The AArch64 va_list type and handling is specified in the Procedure Call
4116 // Standard, section B.4:
4117 //
4118 // struct {
4119 // void *__stack;
4120 // void *__gr_top;
4121 // void *__vr_top;
4122 // int __gr_offs;
4123 // int __vr_offs;
4124 // };
4125
4126 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4127 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4128 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4129 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4130 auto &Ctx = CGF.getContext();
4131
Craig Topper8a13c412014-05-21 05:09:00 +00004132 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004133 int reg_top_index;
4134 int RegSize;
4135 if (AllocatedGPR) {
4136 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
4137 // 3 is the field number of __gr_offs
4138 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4139 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4140 reg_top_index = 1; // field number for __gr_top
4141 RegSize = 8 * AllocatedGPR;
4142 } else {
4143 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
4144 // 4 is the field number of __vr_offs.
4145 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4146 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4147 reg_top_index = 2; // field number for __vr_top
4148 RegSize = 16 * AllocatedVFP;
4149 }
4150
4151 //=======================================
4152 // Find out where argument was passed
4153 //=======================================
4154
4155 // If reg_offs >= 0 we're already using the stack for this type of
4156 // argument. We don't want to keep updating reg_offs (in case it overflows,
4157 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4158 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004159 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004160 UsingStack = CGF.Builder.CreateICmpSGE(
4161 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4162
4163 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4164
4165 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004166 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004167 CGF.EmitBlock(MaybeRegBlock);
4168
4169 // Integer arguments may need to correct register alignment (for example a
4170 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4171 // align __gr_offs to calculate the potential address.
4172 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4173 int Align = Ctx.getTypeAlign(Ty) / 8;
4174
4175 reg_offs = CGF.Builder.CreateAdd(
4176 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4177 "align_regoffs");
4178 reg_offs = CGF.Builder.CreateAnd(
4179 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4180 "aligned_regoffs");
4181 }
4182
4183 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004184 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004185 NewOffset = CGF.Builder.CreateAdd(
4186 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4187 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4188
4189 // Now we're in a position to decide whether this argument really was in
4190 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004191 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004192 InRegs = CGF.Builder.CreateICmpSLE(
4193 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4194
4195 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4196
4197 //=======================================
4198 // Argument was in registers
4199 //=======================================
4200
4201 // Now we emit the code for if the argument was originally passed in
4202 // registers. First start the appropriate block:
4203 CGF.EmitBlock(InRegBlock);
4204
Craig Topper8a13c412014-05-21 05:09:00 +00004205 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004206 reg_top_p =
4207 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4208 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4209 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004210 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004211 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4212
4213 if (IsIndirect) {
4214 // If it's been passed indirectly (actually a struct), whatever we find from
4215 // stored registers or on the stack will actually be a struct **.
4216 MemTy = llvm::PointerType::getUnqual(MemTy);
4217 }
4218
Craig Topper8a13c412014-05-21 05:09:00 +00004219 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004220 uint64_t NumMembers = 0;
4221 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004222 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004223 // Homogeneous aggregates passed in registers will have their elements split
4224 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4225 // qN+1, ...). We reload and store into a temporary local variable
4226 // contiguously.
4227 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4228 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4229 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4230 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4231 int Offset = 0;
4232
4233 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4234 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4235 for (unsigned i = 0; i < NumMembers; ++i) {
4236 llvm::Value *BaseOffset =
4237 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4238 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4239 LoadAddr = CGF.Builder.CreateBitCast(
4240 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4241 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4242
4243 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4244 CGF.Builder.CreateStore(Elem, StoreAddr);
4245 }
4246
4247 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4248 } else {
4249 // Otherwise the object is contiguous in memory
4250 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004251 if (CGF.CGM.getDataLayout().isBigEndian() &&
4252 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004253 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4254 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4255 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4256
4257 BaseAddr = CGF.Builder.CreateAdd(
4258 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4259
4260 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4261 }
4262
4263 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4264 }
4265
4266 CGF.EmitBranch(ContBlock);
4267
4268 //=======================================
4269 // Argument was on the stack
4270 //=======================================
4271 CGF.EmitBlock(OnStackBlock);
4272
Craig Topper8a13c412014-05-21 05:09:00 +00004273 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004274 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4275 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4276
4277 // Again, stack arguments may need realigmnent. In this case both integer and
4278 // floating-point ones might be affected.
4279 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4280 int Align = Ctx.getTypeAlign(Ty) / 8;
4281
4282 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4283
4284 OnStackAddr = CGF.Builder.CreateAdd(
4285 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4286 "align_stack");
4287 OnStackAddr = CGF.Builder.CreateAnd(
4288 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4289 "align_stack");
4290
4291 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4292 }
4293
4294 uint64_t StackSize;
4295 if (IsIndirect)
4296 StackSize = 8;
4297 else
4298 StackSize = Ctx.getTypeSize(Ty) / 8;
4299
4300 // All stack slots are 8 bytes
4301 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4302
4303 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4304 llvm::Value *NewStack =
4305 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4306
4307 // Write the new value of __stack for the next call to va_arg
4308 CGF.Builder.CreateStore(NewStack, stack_p);
4309
4310 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4311 Ctx.getTypeSize(Ty) < 64) {
4312 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4313 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4314
4315 OnStackAddr = CGF.Builder.CreateAdd(
4316 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4317
4318 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4319 }
4320
4321 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4322
4323 CGF.EmitBranch(ContBlock);
4324
4325 //=======================================
4326 // Tidy up
4327 //=======================================
4328 CGF.EmitBlock(ContBlock);
4329
4330 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4331 ResAddr->addIncoming(RegAddr, InRegBlock);
4332 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4333
4334 if (IsIndirect)
4335 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4336
4337 return ResAddr;
4338}
4339
Tim Northover573cbee2014-05-24 12:52:07 +00004340llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004341 CodeGenFunction &CGF) const {
4342 // We do not support va_arg for aggregates or illegal vector types.
4343 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4344 // other cases.
4345 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004346 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004347
4348 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4349 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4350
Craig Topper8a13c412014-05-21 05:09:00 +00004351 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004352 uint64_t Members = 0;
4353 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004354
4355 bool isIndirect = false;
4356 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4357 // be passed indirectly.
4358 if (Size > 16 && !isHA) {
4359 isIndirect = true;
4360 Size = 8;
4361 Align = 8;
4362 }
4363
4364 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4365 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4366
4367 CGBuilderTy &Builder = CGF.Builder;
4368 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4369 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4370
4371 if (isEmptyRecord(getContext(), Ty, true)) {
4372 // These are ignored for parameter passing purposes.
4373 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4374 return Builder.CreateBitCast(Addr, PTy);
4375 }
4376
4377 const uint64_t MinABIAlign = 8;
4378 if (Align > MinABIAlign) {
4379 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4380 Addr = Builder.CreateGEP(Addr, Offset);
4381 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4382 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4383 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4384 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4385 }
4386
4387 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4388 llvm::Value *NextAddr = Builder.CreateGEP(
4389 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4390 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4391
4392 if (isIndirect)
4393 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4394 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4395 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4396
4397 return AddrTyped;
4398}
4399
4400//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004401// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004402//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004403
4404namespace {
4405
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004406class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004407public:
4408 enum ABIKind {
4409 APCS = 0,
4410 AAPCS = 1,
4411 AAPCS_VFP
4412 };
4413
4414private:
4415 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004416 mutable int VFPRegs[16];
4417 const unsigned NumVFPs;
4418 const unsigned NumGPRs;
4419 mutable unsigned AllocatedGPRs;
4420 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004421
4422public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004423 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4424 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004425 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004426 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004427 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004428
John McCall3480ef22011-08-30 01:42:09 +00004429 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004430 switch (getTarget().getTriple().getEnvironment()) {
4431 case llvm::Triple::Android:
4432 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004433 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004434 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004435 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004436 return true;
4437 default:
4438 return false;
4439 }
John McCall3480ef22011-08-30 01:42:09 +00004440 }
4441
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004442 bool isEABIHF() const {
4443 switch (getTarget().getTriple().getEnvironment()) {
4444 case llvm::Triple::EABIHF:
4445 case llvm::Triple::GNUEABIHF:
4446 return true;
4447 default:
4448 return false;
4449 }
4450 }
4451
Daniel Dunbar020daa92009-09-12 01:00:39 +00004452 ABIKind getABIKind() const { return Kind; }
4453
Tim Northovera484bc02013-10-01 14:34:25 +00004454private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004455 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004456 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004457 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004458 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004459
Reid Klecknere9f6a712014-10-31 17:10:41 +00004460 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4461 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4462 uint64_t Members) const override;
4463
Craig Topper4f12f102014-03-12 06:41:41 +00004464 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004465
Craig Topper4f12f102014-03-12 06:41:41 +00004466 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4467 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004468
4469 llvm::CallingConv::ID getLLVMDefaultCC() const;
4470 llvm::CallingConv::ID getABIDefaultCC() const;
4471 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004472
4473 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4474 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4475 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004476};
4477
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004478class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4479public:
Chris Lattner2b037972010-07-29 02:01:43 +00004480 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4481 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004482
John McCall3480ef22011-08-30 01:42:09 +00004483 const ARMABIInfo &getABIInfo() const {
4484 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4485 }
4486
Craig Topper4f12f102014-03-12 06:41:41 +00004487 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004488 return 13;
4489 }
Roman Divackyc1617352011-05-18 19:36:54 +00004490
Craig Topper4f12f102014-03-12 06:41:41 +00004491 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004492 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4493 }
4494
Roman Divackyc1617352011-05-18 19:36:54 +00004495 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004496 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004497 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004498
4499 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004500 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004501 return false;
4502 }
John McCall3480ef22011-08-30 01:42:09 +00004503
Craig Topper4f12f102014-03-12 06:41:41 +00004504 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004505 if (getABIInfo().isEABI()) return 88;
4506 return TargetCodeGenInfo::getSizeOfUnwindException();
4507 }
Tim Northovera484bc02013-10-01 14:34:25 +00004508
4509 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004510 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004511 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4512 if (!FD)
4513 return;
4514
4515 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4516 if (!Attr)
4517 return;
4518
4519 const char *Kind;
4520 switch (Attr->getInterrupt()) {
4521 case ARMInterruptAttr::Generic: Kind = ""; break;
4522 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4523 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4524 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4525 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4526 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4527 }
4528
4529 llvm::Function *Fn = cast<llvm::Function>(GV);
4530
4531 Fn->addFnAttr("interrupt", Kind);
4532
4533 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4534 return;
4535
4536 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4537 // however this is not necessarily true on taking any interrupt. Instruct
4538 // the backend to perform a realignment as part of the function prologue.
4539 llvm::AttrBuilder B;
4540 B.addStackAlignmentAttr(8);
4541 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4542 llvm::AttributeSet::get(CGM.getLLVMContext(),
4543 llvm::AttributeSet::FunctionIndex,
4544 B));
4545 }
4546
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004547};
4548
Daniel Dunbard59655c2009-09-12 00:59:49 +00004549}
4550
Chris Lattner22326a12010-07-29 02:31:05 +00004551void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004552 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004553 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004554 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4555 // VFP registers of the appropriate type unallocated then the argument is
4556 // allocated to the lowest-numbered sequence of such registers.
4557 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4558 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004559 resetAllocatedRegs();
4560
Reid Kleckner40ca9132014-05-13 22:05:45 +00004561 if (getCXXABI().classifyReturnType(FI)) {
4562 if (FI.getReturnInfo().isIndirect())
4563 markAllocatedGPRs(1, 1);
4564 } else {
4565 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4566 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004567 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004568 unsigned PreAllocationVFPs = AllocatedVFPs;
4569 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004570 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004571 // 6.1.2.3 There is one VFP co-processor register class using registers
4572 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004573 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004574
4575 // If we have allocated some arguments onto the stack (due to running
4576 // out of VFP registers), we cannot split an argument between GPRs and
4577 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004578 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004579 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4580 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004581 // We do not have to do this if the argument is being passed ByVal, as the
4582 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004583 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004584 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4585 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4586 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004587 llvm::Type *PaddingTy = llvm::ArrayType::get(
4588 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004589 if (I.info.canHaveCoerceToType()) {
Tim Northover5a1558e2014-11-07 22:30:50 +00004590 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */,
4591 0 /* offset */, PaddingTy, true);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004592 } else {
4593 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Tim Northover5a1558e2014-11-07 22:30:50 +00004594 PaddingTy, true);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004595 }
Manman Ren2a523d82012-10-30 23:21:41 +00004596 }
4597 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004598
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004599 // Always honor user-specified calling convention.
4600 if (FI.getCallingConvention() != llvm::CallingConv::C)
4601 return;
4602
John McCall882987f2013-02-28 19:01:20 +00004603 llvm::CallingConv::ID cc = getRuntimeCC();
4604 if (cc != llvm::CallingConv::C)
4605 FI.setEffectiveCallingConvention(cc);
4606}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004607
John McCall882987f2013-02-28 19:01:20 +00004608/// Return the default calling convention that LLVM will use.
4609llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4610 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004611 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004612 return llvm::CallingConv::ARM_AAPCS_VFP;
4613 else if (isEABI())
4614 return llvm::CallingConv::ARM_AAPCS;
4615 else
4616 return llvm::CallingConv::ARM_APCS;
4617}
4618
4619/// Return the calling convention that our ABI would like us to use
4620/// as the C calling convention.
4621llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004622 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004623 case APCS: return llvm::CallingConv::ARM_APCS;
4624 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4625 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004626 }
John McCall882987f2013-02-28 19:01:20 +00004627 llvm_unreachable("bad ABI kind");
4628}
4629
4630void ARMABIInfo::setRuntimeCC() {
4631 assert(getRuntimeCC() == llvm::CallingConv::C);
4632
4633 // Don't muddy up the IR with a ton of explicit annotations if
4634 // they'd just match what LLVM will infer from the triple.
4635 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4636 if (abiCC != getLLVMDefaultCC())
4637 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004638}
4639
Manman Renb505d332012-10-31 19:02:26 +00004640/// markAllocatedVFPs - update VFPRegs according to the alignment and
4641/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004642void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4643 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004644 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004645 if (AllocatedVFPs >= 16) {
4646 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4647 // the stack.
4648 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004649 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004650 }
Manman Renb505d332012-10-31 19:02:26 +00004651 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4652 // VFP registers of the appropriate type unallocated then the argument is
4653 // allocated to the lowest-numbered sequence of such registers.
4654 for (unsigned I = 0; I < 16; I += Alignment) {
4655 bool FoundSlot = true;
4656 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4657 if (J >= 16 || VFPRegs[J]) {
4658 FoundSlot = false;
4659 break;
4660 }
4661 if (FoundSlot) {
4662 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4663 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004664 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004665 return;
4666 }
4667 }
4668 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4669 // unallocated are marked as unavailable.
4670 for (unsigned I = 0; I < 16; I++)
4671 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004672 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004673}
4674
Oliver Stannard405bded2014-02-11 09:25:50 +00004675/// Update AllocatedGPRs to record the number of general purpose registers
4676/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4677/// this represents arguments being stored on the stack.
4678void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004679 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004680 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4681
4682 if (Alignment == 2 && AllocatedGPRs & 0x1)
4683 AllocatedGPRs += 1;
4684
4685 AllocatedGPRs += NumRequired;
4686}
4687
4688void ARMABIInfo::resetAllocatedRegs(void) const {
4689 AllocatedGPRs = 0;
4690 AllocatedVFPs = 0;
4691 for (unsigned i = 0; i < NumVFPs; ++i)
4692 VFPRegs[i] = 0;
4693}
4694
James Molloy6f244b62014-05-09 16:21:39 +00004695ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004696 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004697 // We update number of allocated VFPs according to
4698 // 6.1.2.1 The following argument types are VFP CPRCs:
4699 // A single-precision floating-point type (including promoted
4700 // half-precision types); A double-precision floating-point type;
4701 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4702 // with a Base Type of a single- or double-precision floating-point type,
4703 // 64-bit containerized vectors or 128-bit containerized vectors with one
4704 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004705 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004706
Reid Klecknerb1be6832014-11-15 01:41:41 +00004707 Ty = useFirstFieldIfTransparentUnion(Ty);
4708
Manman Renfef9e312012-10-16 19:18:39 +00004709 // Handle illegal vector types here.
4710 if (isIllegalVectorType(Ty)) {
4711 uint64_t Size = getContext().getTypeSize(Ty);
4712 if (Size <= 32) {
4713 llvm::Type *ResType =
4714 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004715 markAllocatedGPRs(1, 1);
Tim Northover5a1558e2014-11-07 22:30:50 +00004716 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004717 }
4718 if (Size == 64) {
4719 llvm::Type *ResType = llvm::VectorType::get(
4720 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004721 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4722 markAllocatedGPRs(2, 2);
4723 } else {
4724 markAllocatedVFPs(2, 2);
4725 IsCPRC = true;
4726 }
Tim Northover5a1558e2014-11-07 22:30:50 +00004727 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004728 }
4729 if (Size == 128) {
4730 llvm::Type *ResType = llvm::VectorType::get(
4731 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004732 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4733 markAllocatedGPRs(2, 4);
4734 } else {
4735 markAllocatedVFPs(4, 4);
4736 IsCPRC = true;
4737 }
Tim Northover5a1558e2014-11-07 22:30:50 +00004738 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004739 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004740 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004741 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4742 }
Manman Renb505d332012-10-31 19:02:26 +00004743 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004744 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4745 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4746 uint64_t Size = getContext().getTypeSize(VT);
4747 // Size of a legal vector should be power of 2 and above 64.
4748 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4749 IsCPRC = true;
4750 }
Manman Ren2a523d82012-10-30 23:21:41 +00004751 }
Manman Renb505d332012-10-31 19:02:26 +00004752 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004753 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4754 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4755 if (BT->getKind() == BuiltinType::Half ||
4756 BT->getKind() == BuiltinType::Float) {
4757 markAllocatedVFPs(1, 1);
4758 IsCPRC = true;
4759 }
4760 if (BT->getKind() == BuiltinType::Double ||
4761 BT->getKind() == BuiltinType::LongDouble) {
4762 markAllocatedVFPs(2, 2);
4763 IsCPRC = true;
4764 }
4765 }
Manman Ren2a523d82012-10-30 23:21:41 +00004766 }
Manman Renfef9e312012-10-16 19:18:39 +00004767
John McCalla1dee5302010-08-22 10:59:02 +00004768 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004769 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004770 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004771 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004772 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004773
Oliver Stannard405bded2014-02-11 09:25:50 +00004774 unsigned Size = getContext().getTypeSize(Ty);
4775 if (!IsCPRC)
4776 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Tim Northover5a1558e2014-11-07 22:30:50 +00004777 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4778 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004779 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004780
Oliver Stannard405bded2014-02-11 09:25:50 +00004781 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4782 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004783 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004784 }
Tim Northover1060eae2013-06-21 22:49:34 +00004785
Daniel Dunbar09d33622009-09-14 21:54:03 +00004786 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004787 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004788 return ABIArgInfo::getIgnore();
4789
Tim Northover5a1558e2014-11-07 22:30:50 +00004790 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004791 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4792 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004793 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004794 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004795 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004796 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004797 // Base can be a floating-point or a vector.
4798 if (Base->isVectorType()) {
4799 // ElementSize is in number of floats.
4800 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004801 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004802 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004803 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004804 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004805 else {
4806 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4807 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004808 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004809 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004810 IsCPRC = true;
Tim Northover5a1558e2014-11-07 22:30:50 +00004811 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004812 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004813 }
4814
Manman Ren6c30e132012-08-13 21:23:55 +00004815 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004816 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4817 // most 8-byte. We realign the indirect argument if type alignment is bigger
4818 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004819 uint64_t ABIAlign = 4;
4820 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4821 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4822 getABIKind() == ARMABIInfo::AAPCS)
4823 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004824 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004825 // Update Allocated GPRs. Since this is only used when the size of the
4826 // argument is greater than 64 bytes, this will always use up any available
4827 // registers (of which there are 4). We also don't care about getting the
4828 // alignment right, because general-purpose registers cannot be back-filled.
4829 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004830 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004831 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004832 }
4833
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004834 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004835 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004836 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004837 // FIXME: Try to match the types of the arguments more accurately where
4838 // we can.
4839 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004840 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4841 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004842 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004843 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004844 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4845 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004846 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004847 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004848
Tim Northover5a1558e2014-11-07 22:30:50 +00004849 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004850}
4851
Chris Lattner458b2aa2010-07-29 02:16:43 +00004852static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004853 llvm::LLVMContext &VMContext) {
4854 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4855 // is called integer-like if its size is less than or equal to one word, and
4856 // the offset of each of its addressable sub-fields is zero.
4857
4858 uint64_t Size = Context.getTypeSize(Ty);
4859
4860 // Check that the type fits in a word.
4861 if (Size > 32)
4862 return false;
4863
4864 // FIXME: Handle vector types!
4865 if (Ty->isVectorType())
4866 return false;
4867
Daniel Dunbard53bac72009-09-14 02:20:34 +00004868 // Float types are never treated as "integer like".
4869 if (Ty->isRealFloatingType())
4870 return false;
4871
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004872 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004873 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004874 return true;
4875
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004876 // Small complex integer types are "integer like".
4877 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4878 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004879
4880 // Single element and zero sized arrays should be allowed, by the definition
4881 // above, but they are not.
4882
4883 // Otherwise, it must be a record type.
4884 const RecordType *RT = Ty->getAs<RecordType>();
4885 if (!RT) return false;
4886
4887 // Ignore records with flexible arrays.
4888 const RecordDecl *RD = RT->getDecl();
4889 if (RD->hasFlexibleArrayMember())
4890 return false;
4891
4892 // Check that all sub-fields are at offset 0, and are themselves "integer
4893 // like".
4894 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4895
4896 bool HadField = false;
4897 unsigned idx = 0;
4898 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4899 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004900 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004901
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004902 // Bit-fields are not addressable, we only need to verify they are "integer
4903 // like". We still have to disallow a subsequent non-bitfield, for example:
4904 // struct { int : 0; int x }
4905 // is non-integer like according to gcc.
4906 if (FD->isBitField()) {
4907 if (!RD->isUnion())
4908 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004909
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004910 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4911 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004912
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004913 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004914 }
4915
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004916 // Check if this field is at offset 0.
4917 if (Layout.getFieldOffset(idx) != 0)
4918 return false;
4919
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004920 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4921 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004922
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004923 // Only allow at most one field in a structure. This doesn't match the
4924 // wording above, but follows gcc in situations with a field following an
4925 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004926 if (!RD->isUnion()) {
4927 if (HadField)
4928 return false;
4929
4930 HadField = true;
4931 }
4932 }
4933
4934 return true;
4935}
4936
Oliver Stannard405bded2014-02-11 09:25:50 +00004937ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4938 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004939 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004940
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004941 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004942 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004943
Daniel Dunbar19964db2010-09-23 01:54:32 +00004944 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004945 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4946 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004947 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004948 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004949
John McCalla1dee5302010-08-22 10:59:02 +00004950 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004951 // Treat an enum type as its underlying type.
4952 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4953 RetTy = EnumTy->getDecl()->getIntegerType();
4954
Tim Northover5a1558e2014-11-07 22:30:50 +00004955 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4956 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004957 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004958
4959 // Are we following APCS?
4960 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004961 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004962 return ABIArgInfo::getIgnore();
4963
Daniel Dunbareedf1512010-02-01 23:31:19 +00004964 // Complex types are all returned as packed integers.
4965 //
4966 // FIXME: Consider using 2 x vector types if the back end handles them
4967 // correctly.
4968 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004969 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4970 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004971
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004972 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004973 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004974 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004975 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004976 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004977 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004978 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004979 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4980 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004981 }
4982
4983 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004984 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004985 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004986 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004987
4988 // Otherwise this is an AAPCS variant.
4989
Chris Lattner458b2aa2010-07-29 02:16:43 +00004990 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004991 return ABIArgInfo::getIgnore();
4992
Bob Wilson1d9269a2011-11-02 04:51:36 +00004993 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004994 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004995 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004996 uint64_t Members;
4997 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004998 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004999 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005000 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005001 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005002 }
5003
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005004 // Aggregates <= 4 bytes are returned in r0; other aggregates
5005 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005006 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005007 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005008 if (getDataLayout().isBigEndian())
5009 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005010 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005011
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005012 // Return in the smallest viable integer type.
5013 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005014 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005015 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005016 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5017 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005018 }
5019
Oliver Stannard405bded2014-02-11 09:25:50 +00005020 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005021 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005022}
5023
Manman Renfef9e312012-10-16 19:18:39 +00005024/// isIllegalVector - check whether Ty is an illegal vector type.
5025bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5026 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5027 // Check whether VT is legal.
5028 unsigned NumElements = VT->getNumElements();
5029 uint64_t Size = getContext().getTypeSize(VT);
5030 // NumElements should be power of 2.
5031 if ((NumElements & (NumElements - 1)) != 0)
5032 return true;
5033 // Size should be greater than 32 bits.
5034 return Size <= 32;
5035 }
5036 return false;
5037}
5038
Reid Klecknere9f6a712014-10-31 17:10:41 +00005039bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5040 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5041 // double, or 64-bit or 128-bit vectors.
5042 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5043 if (BT->getKind() == BuiltinType::Float ||
5044 BT->getKind() == BuiltinType::Double ||
5045 BT->getKind() == BuiltinType::LongDouble)
5046 return true;
5047 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5048 unsigned VecSize = getContext().getTypeSize(VT);
5049 if (VecSize == 64 || VecSize == 128)
5050 return true;
5051 }
5052 return false;
5053}
5054
5055bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5056 uint64_t Members) const {
5057 return Members <= 4;
5058}
5059
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005060llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00005061 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005062 llvm::Type *BP = CGF.Int8PtrTy;
5063 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005064
5065 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00005066 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005067 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00005068
Tim Northover1711cc92013-06-21 23:05:33 +00005069 if (isEmptyRecord(getContext(), Ty, true)) {
5070 // These are ignored for parameter passing purposes.
5071 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5072 return Builder.CreateBitCast(Addr, PTy);
5073 }
5074
Manman Rencca54d02012-10-16 19:01:37 +00005075 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00005076 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00005077 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00005078
5079 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5080 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00005081 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5082 getABIKind() == ARMABIInfo::AAPCS)
5083 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5084 else
5085 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00005086 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5087 if (isIllegalVectorType(Ty) && Size > 16) {
5088 IsIndirect = true;
5089 Size = 4;
5090 TyAlign = 4;
5091 }
Manman Rencca54d02012-10-16 19:01:37 +00005092
5093 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005094 if (TyAlign > 4) {
5095 assert((TyAlign & (TyAlign - 1)) == 0 &&
5096 "Alignment is not power of 2!");
5097 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5098 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5099 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005100 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005101 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005102
5103 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005104 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005105 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005106 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005107 "ap.next");
5108 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5109
Manman Renfef9e312012-10-16 19:18:39 +00005110 if (IsIndirect)
5111 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005112 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005113 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5114 // may not be correctly aligned for the vector type. We create an aligned
5115 // temporary space and copy the content over from ap.cur to the temporary
5116 // space. This is necessary if the natural alignment of the type is greater
5117 // than the ABI alignment.
5118 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5119 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5120 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5121 "var.align");
5122 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5123 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5124 Builder.CreateMemCpy(Dst, Src,
5125 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5126 TyAlign, false);
5127 Addr = AlignedTemp; //The content is in aligned location.
5128 }
5129 llvm::Type *PTy =
5130 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5131 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005133 return AddrTyped;
5134}
5135
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005136namespace {
5137
Derek Schuffa2020962012-10-16 22:30:41 +00005138class NaClARMABIInfo : public ABIInfo {
5139 public:
5140 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5141 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005142 void computeInfo(CGFunctionInfo &FI) const override;
5143 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5144 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00005145 private:
5146 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
5147 ARMABIInfo NInfo; // Used for everything else.
5148};
5149
5150class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
5151 public:
5152 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5153 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
5154};
5155
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005156}
5157
Derek Schuffa2020962012-10-16 22:30:41 +00005158void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5159 if (FI.getASTCallingConvention() == CC_PnaclCall)
5160 PInfo.computeInfo(FI);
5161 else
5162 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
5163}
5164
5165llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5166 CodeGenFunction &CGF) const {
5167 // Always use the native convention; calling pnacl-style varargs functions
5168 // is unsupported.
5169 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
5170}
5171
Chris Lattner0cf24192010-06-28 20:05:43 +00005172//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005173// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005174//===----------------------------------------------------------------------===//
5175
5176namespace {
5177
Justin Holewinski83e96682012-05-24 17:43:12 +00005178class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005179public:
Justin Holewinski36837432013-03-30 14:38:24 +00005180 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005181
5182 ABIArgInfo classifyReturnType(QualType RetTy) const;
5183 ABIArgInfo classifyArgumentType(QualType Ty) const;
5184
Craig Topper4f12f102014-03-12 06:41:41 +00005185 void computeInfo(CGFunctionInfo &FI) const override;
5186 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5187 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005188};
5189
Justin Holewinski83e96682012-05-24 17:43:12 +00005190class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005191public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005192 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5193 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005194
5195 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5196 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005197private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005198 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5199 // resulting MDNode to the nvvm.annotations MDNode.
5200 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005201};
5202
Justin Holewinski83e96682012-05-24 17:43:12 +00005203ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005204 if (RetTy->isVoidType())
5205 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005206
5207 // note: this is different from default ABI
5208 if (!RetTy->isScalarType())
5209 return ABIArgInfo::getDirect();
5210
5211 // Treat an enum type as its underlying type.
5212 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5213 RetTy = EnumTy->getDecl()->getIntegerType();
5214
5215 return (RetTy->isPromotableIntegerType() ?
5216 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005217}
5218
Justin Holewinski83e96682012-05-24 17:43:12 +00005219ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005220 // Treat an enum type as its underlying type.
5221 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5222 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005223
Eli Bendersky95338a02014-10-29 13:43:21 +00005224 // Return aggregates type as indirect by value
5225 if (isAggregateTypeForABI(Ty))
5226 return ABIArgInfo::getIndirect(0, /* byval */ true);
5227
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005228 return (Ty->isPromotableIntegerType() ?
5229 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005230}
5231
Justin Holewinski83e96682012-05-24 17:43:12 +00005232void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005233 if (!getCXXABI().classifyReturnType(FI))
5234 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005235 for (auto &I : FI.arguments())
5236 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005237
5238 // Always honor user-specified calling convention.
5239 if (FI.getCallingConvention() != llvm::CallingConv::C)
5240 return;
5241
John McCall882987f2013-02-28 19:01:20 +00005242 FI.setEffectiveCallingConvention(getRuntimeCC());
5243}
5244
Justin Holewinski83e96682012-05-24 17:43:12 +00005245llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5246 CodeGenFunction &CFG) const {
5247 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005248}
5249
Justin Holewinski83e96682012-05-24 17:43:12 +00005250void NVPTXTargetCodeGenInfo::
5251SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5252 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005253 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5254 if (!FD) return;
5255
5256 llvm::Function *F = cast<llvm::Function>(GV);
5257
5258 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005259 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005260 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005261 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005262 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005263 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005264 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5265 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005266 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005267 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005268 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005269 }
Justin Holewinski38031972011-10-05 17:58:44 +00005270
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005271 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005272 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005273 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005274 // __global__ functions cannot be called from the device, we do not
5275 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005276 if (FD->hasAttr<CUDAGlobalAttr>()) {
5277 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5278 addNVVMMetadata(F, "kernel", 1);
5279 }
5280 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5281 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5282 addNVVMMetadata(F, "maxntidx",
5283 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5284 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5285 // zero value from getMinBlocks either means it was not specified in
5286 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5287 // don't have to add a PTX directive.
5288 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5289 if (MinCTASM > 0) {
5290 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5291 addNVVMMetadata(F, "minctasm", MinCTASM);
5292 }
5293 }
Justin Holewinski38031972011-10-05 17:58:44 +00005294 }
5295}
5296
Eli Benderskye06a2c42014-04-15 16:57:05 +00005297void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5298 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005299 llvm::Module *M = F->getParent();
5300 llvm::LLVMContext &Ctx = M->getContext();
5301
5302 // Get "nvvm.annotations" metadata node
5303 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5304
Eli Benderskye1627b42014-04-15 17:19:26 +00005305 llvm::Value *MDVals[] = {
5306 F, llvm::MDString::get(Ctx, Name),
5307 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005308 // Append metadata to nvvm.annotations
5309 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5310}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005311}
5312
5313//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005314// SystemZ ABI Implementation
5315//===----------------------------------------------------------------------===//
5316
5317namespace {
5318
5319class SystemZABIInfo : public ABIInfo {
5320public:
5321 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5322
5323 bool isPromotableIntegerType(QualType Ty) const;
5324 bool isCompoundType(QualType Ty) const;
5325 bool isFPArgumentType(QualType Ty) const;
5326
5327 ABIArgInfo classifyReturnType(QualType RetTy) const;
5328 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5329
Craig Topper4f12f102014-03-12 06:41:41 +00005330 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005331 if (!getCXXABI().classifyReturnType(FI))
5332 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005333 for (auto &I : FI.arguments())
5334 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005335 }
5336
Craig Topper4f12f102014-03-12 06:41:41 +00005337 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5338 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005339};
5340
5341class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5342public:
5343 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5344 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5345};
5346
5347}
5348
5349bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5350 // Treat an enum type as its underlying type.
5351 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5352 Ty = EnumTy->getDecl()->getIntegerType();
5353
5354 // Promotable integer types are required to be promoted by the ABI.
5355 if (Ty->isPromotableIntegerType())
5356 return true;
5357
5358 // 32-bit values must also be promoted.
5359 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5360 switch (BT->getKind()) {
5361 case BuiltinType::Int:
5362 case BuiltinType::UInt:
5363 return true;
5364 default:
5365 return false;
5366 }
5367 return false;
5368}
5369
5370bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5371 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5372}
5373
5374bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5375 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5376 switch (BT->getKind()) {
5377 case BuiltinType::Float:
5378 case BuiltinType::Double:
5379 return true;
5380 default:
5381 return false;
5382 }
5383
5384 if (const RecordType *RT = Ty->getAsStructureType()) {
5385 const RecordDecl *RD = RT->getDecl();
5386 bool Found = false;
5387
5388 // If this is a C++ record, check the bases first.
5389 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005390 for (const auto &I : CXXRD->bases()) {
5391 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005392
5393 // Empty bases don't affect things either way.
5394 if (isEmptyRecord(getContext(), Base, true))
5395 continue;
5396
5397 if (Found)
5398 return false;
5399 Found = isFPArgumentType(Base);
5400 if (!Found)
5401 return false;
5402 }
5403
5404 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005405 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005406 // Empty bitfields don't affect things either way.
5407 // Unlike isSingleElementStruct(), empty structure and array fields
5408 // do count. So do anonymous bitfields that aren't zero-sized.
5409 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5410 return true;
5411
5412 // Unlike isSingleElementStruct(), arrays do not count.
5413 // Nested isFPArgumentType structures still do though.
5414 if (Found)
5415 return false;
5416 Found = isFPArgumentType(FD->getType());
5417 if (!Found)
5418 return false;
5419 }
5420
5421 // Unlike isSingleElementStruct(), trailing padding is allowed.
5422 // An 8-byte aligned struct s { float f; } is passed as a double.
5423 return Found;
5424 }
5425
5426 return false;
5427}
5428
5429llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5430 CodeGenFunction &CGF) const {
5431 // Assume that va_list type is correct; should be pointer to LLVM type:
5432 // struct {
5433 // i64 __gpr;
5434 // i64 __fpr;
5435 // i8 *__overflow_arg_area;
5436 // i8 *__reg_save_area;
5437 // };
5438
5439 // Every argument occupies 8 bytes and is passed by preference in either
5440 // GPRs or FPRs.
5441 Ty = CGF.getContext().getCanonicalType(Ty);
5442 ABIArgInfo AI = classifyArgumentType(Ty);
5443 bool InFPRs = isFPArgumentType(Ty);
5444
5445 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5446 bool IsIndirect = AI.isIndirect();
5447 unsigned UnpaddedBitSize;
5448 if (IsIndirect) {
5449 APTy = llvm::PointerType::getUnqual(APTy);
5450 UnpaddedBitSize = 64;
5451 } else
5452 UnpaddedBitSize = getContext().getTypeSize(Ty);
5453 unsigned PaddedBitSize = 64;
5454 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5455
5456 unsigned PaddedSize = PaddedBitSize / 8;
5457 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5458
5459 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5460 if (InFPRs) {
5461 MaxRegs = 4; // Maximum of 4 FPR arguments
5462 RegCountField = 1; // __fpr
5463 RegSaveIndex = 16; // save offset for f0
5464 RegPadding = 0; // floats are passed in the high bits of an FPR
5465 } else {
5466 MaxRegs = 5; // Maximum of 5 GPR arguments
5467 RegCountField = 0; // __gpr
5468 RegSaveIndex = 2; // save offset for r2
5469 RegPadding = Padding; // values are passed in the low bits of a GPR
5470 }
5471
5472 llvm::Value *RegCountPtr =
5473 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5474 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5475 llvm::Type *IndexTy = RegCount->getType();
5476 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5477 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005478 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005479
5480 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5481 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5482 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5483 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5484
5485 // Emit code to load the value if it was passed in registers.
5486 CGF.EmitBlock(InRegBlock);
5487
5488 // Work out the address of an argument register.
5489 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5490 llvm::Value *ScaledRegCount =
5491 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5492 llvm::Value *RegBase =
5493 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5494 llvm::Value *RegOffset =
5495 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5496 llvm::Value *RegSaveAreaPtr =
5497 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5498 llvm::Value *RegSaveArea =
5499 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5500 llvm::Value *RawRegAddr =
5501 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5502 llvm::Value *RegAddr =
5503 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5504
5505 // Update the register count
5506 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5507 llvm::Value *NewRegCount =
5508 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5509 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5510 CGF.EmitBranch(ContBlock);
5511
5512 // Emit code to load the value if it was passed in memory.
5513 CGF.EmitBlock(InMemBlock);
5514
5515 // Work out the address of a stack argument.
5516 llvm::Value *OverflowArgAreaPtr =
5517 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5518 llvm::Value *OverflowArgArea =
5519 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5520 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5521 llvm::Value *RawMemAddr =
5522 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5523 llvm::Value *MemAddr =
5524 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5525
5526 // Update overflow_arg_area_ptr pointer
5527 llvm::Value *NewOverflowArgArea =
5528 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5529 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5530 CGF.EmitBranch(ContBlock);
5531
5532 // Return the appropriate result.
5533 CGF.EmitBlock(ContBlock);
5534 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5535 ResAddr->addIncoming(RegAddr, InRegBlock);
5536 ResAddr->addIncoming(MemAddr, InMemBlock);
5537
5538 if (IsIndirect)
5539 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5540
5541 return ResAddr;
5542}
5543
Ulrich Weigand47445072013-05-06 16:26:41 +00005544ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5545 if (RetTy->isVoidType())
5546 return ABIArgInfo::getIgnore();
5547 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5548 return ABIArgInfo::getIndirect(0);
5549 return (isPromotableIntegerType(RetTy) ?
5550 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5551}
5552
5553ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5554 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005555 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005556 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5557
5558 // Integers and enums are extended to full register width.
5559 if (isPromotableIntegerType(Ty))
5560 return ABIArgInfo::getExtend();
5561
5562 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5563 uint64_t Size = getContext().getTypeSize(Ty);
5564 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005565 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005566
5567 // Handle small structures.
5568 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5569 // Structures with flexible arrays have variable length, so really
5570 // fail the size test above.
5571 const RecordDecl *RD = RT->getDecl();
5572 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005573 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005574
5575 // The structure is passed as an unextended integer, a float, or a double.
5576 llvm::Type *PassTy;
5577 if (isFPArgumentType(Ty)) {
5578 assert(Size == 32 || Size == 64);
5579 if (Size == 32)
5580 PassTy = llvm::Type::getFloatTy(getVMContext());
5581 else
5582 PassTy = llvm::Type::getDoubleTy(getVMContext());
5583 } else
5584 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5585 return ABIArgInfo::getDirect(PassTy);
5586 }
5587
5588 // Non-structure compounds are passed indirectly.
5589 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005590 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005591
Craig Topper8a13c412014-05-21 05:09:00 +00005592 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005593}
5594
5595//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005596// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005597//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005598
5599namespace {
5600
5601class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5602public:
Chris Lattner2b037972010-07-29 02:01:43 +00005603 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5604 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005605 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005606 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005607};
5608
5609}
5610
5611void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5612 llvm::GlobalValue *GV,
5613 CodeGen::CodeGenModule &M) const {
5614 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5615 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5616 // Handle 'interrupt' attribute:
5617 llvm::Function *F = cast<llvm::Function>(GV);
5618
5619 // Step 1: Set ISR calling convention.
5620 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5621
5622 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005623 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005624
5625 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005626 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005627 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5628 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005629 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005630 }
5631}
5632
Chris Lattner0cf24192010-06-28 20:05:43 +00005633//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005634// MIPS ABI Implementation. This works for both little-endian and
5635// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005636//===----------------------------------------------------------------------===//
5637
John McCall943fae92010-05-27 06:19:26 +00005638namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005639class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005640 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005641 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5642 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005643 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005644 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005645 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005646 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005647public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005648 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005649 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005650 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005651
5652 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005653 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005654 void computeInfo(CGFunctionInfo &FI) const override;
5655 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5656 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005657};
5658
John McCall943fae92010-05-27 06:19:26 +00005659class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005660 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005661public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005662 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5663 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005664 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005665
Craig Topper4f12f102014-03-12 06:41:41 +00005666 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005667 return 29;
5668 }
5669
Reed Kotler373feca2013-01-16 17:10:28 +00005670 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005671 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005672 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5673 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005674 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005675 if (FD->hasAttr<Mips16Attr>()) {
5676 Fn->addFnAttr("mips16");
5677 }
5678 else if (FD->hasAttr<NoMips16Attr>()) {
5679 Fn->addFnAttr("nomips16");
5680 }
Reed Kotler373feca2013-01-16 17:10:28 +00005681 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005682
John McCall943fae92010-05-27 06:19:26 +00005683 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005684 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005685
Craig Topper4f12f102014-03-12 06:41:41 +00005686 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005687 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005688 }
John McCall943fae92010-05-27 06:19:26 +00005689};
5690}
5691
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005692void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005693 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005694 llvm::IntegerType *IntTy =
5695 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005696
5697 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5698 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5699 ArgList.push_back(IntTy);
5700
5701 // If necessary, add one more integer type to ArgList.
5702 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5703
5704 if (R)
5705 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005706}
5707
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005708// In N32/64, an aligned double precision floating point field is passed in
5709// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005710llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005711 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5712
5713 if (IsO32) {
5714 CoerceToIntArgs(TySize, ArgList);
5715 return llvm::StructType::get(getVMContext(), ArgList);
5716 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005717
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005718 if (Ty->isComplexType())
5719 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005720
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005721 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005722
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005723 // Unions/vectors are passed in integer registers.
5724 if (!RT || !RT->isStructureOrClassType()) {
5725 CoerceToIntArgs(TySize, ArgList);
5726 return llvm::StructType::get(getVMContext(), ArgList);
5727 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005728
5729 const RecordDecl *RD = RT->getDecl();
5730 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005731 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005732
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005733 uint64_t LastOffset = 0;
5734 unsigned idx = 0;
5735 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5736
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005737 // Iterate over fields in the struct/class and check if there are any aligned
5738 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005739 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5740 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005741 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005742 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5743
5744 if (!BT || BT->getKind() != BuiltinType::Double)
5745 continue;
5746
5747 uint64_t Offset = Layout.getFieldOffset(idx);
5748 if (Offset % 64) // Ignore doubles that are not aligned.
5749 continue;
5750
5751 // Add ((Offset - LastOffset) / 64) args of type i64.
5752 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5753 ArgList.push_back(I64);
5754
5755 // Add double type.
5756 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5757 LastOffset = Offset + 64;
5758 }
5759
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005760 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5761 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005762
5763 return llvm::StructType::get(getVMContext(), ArgList);
5764}
5765
Akira Hatanakaddd66342013-10-29 18:41:15 +00005766llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5767 uint64_t Offset) const {
5768 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005769 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005770
Akira Hatanakaddd66342013-10-29 18:41:15 +00005771 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005772}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005773
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005774ABIArgInfo
5775MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005776 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005777 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005778 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005779
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005780 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5781 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005782 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5783 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005784
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005785 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005786 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005787 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005788 return ABIArgInfo::getIgnore();
5789
Mark Lacey3825e832013-10-06 01:33:34 +00005790 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005791 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005792 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005793 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005794
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005795 // If we have reached here, aggregates are passed directly by coercing to
5796 // another structure type. Padding is inserted if the offset of the
5797 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005798 ABIArgInfo ArgInfo =
5799 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5800 getPaddingType(OrigOffset, CurrOffset));
5801 ArgInfo.setInReg(true);
5802 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005803 }
5804
5805 // Treat an enum type as its underlying type.
5806 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5807 Ty = EnumTy->getDecl()->getIntegerType();
5808
Daniel Sanders5b445b32014-10-24 14:42:42 +00005809 // All integral types are promoted to the GPR width.
5810 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005811 return ABIArgInfo::getExtend();
5812
Akira Hatanakaddd66342013-10-29 18:41:15 +00005813 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005814 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005815}
5816
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005817llvm::Type*
5818MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005819 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005820 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005821
Akira Hatanakab6f74432012-02-09 18:49:26 +00005822 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005823 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005824 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5825 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005826
Akira Hatanakab6f74432012-02-09 18:49:26 +00005827 // N32/64 returns struct/classes in floating point registers if the
5828 // following conditions are met:
5829 // 1. The size of the struct/class is no larger than 128-bit.
5830 // 2. The struct/class has one or two fields all of which are floating
5831 // point types.
5832 // 3. The offset of the first field is zero (this follows what gcc does).
5833 //
5834 // Any other composite results are returned in integer registers.
5835 //
5836 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5837 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5838 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005839 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005840
Akira Hatanakab6f74432012-02-09 18:49:26 +00005841 if (!BT || !BT->isFloatingPoint())
5842 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005843
David Blaikie2d7c57e2012-04-30 02:36:29 +00005844 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005845 }
5846
5847 if (b == e)
5848 return llvm::StructType::get(getVMContext(), RTList,
5849 RD->hasAttr<PackedAttr>());
5850
5851 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005852 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005853 }
5854
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005855 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005856 return llvm::StructType::get(getVMContext(), RTList);
5857}
5858
Akira Hatanakab579fe52011-06-02 00:09:17 +00005859ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005860 uint64_t Size = getContext().getTypeSize(RetTy);
5861
Daniel Sandersed39f582014-09-04 13:28:14 +00005862 if (RetTy->isVoidType())
5863 return ABIArgInfo::getIgnore();
5864
5865 // O32 doesn't treat zero-sized structs differently from other structs.
5866 // However, N32/N64 ignores zero sized return values.
5867 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005868 return ABIArgInfo::getIgnore();
5869
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005870 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005871 if (Size <= 128) {
5872 if (RetTy->isAnyComplexType())
5873 return ABIArgInfo::getDirect();
5874
Daniel Sanderse5018b62014-09-04 15:05:39 +00005875 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005876 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005877 if (!IsO32 ||
5878 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5879 ABIArgInfo ArgInfo =
5880 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5881 ArgInfo.setInReg(true);
5882 return ArgInfo;
5883 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005884 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005885
5886 return ABIArgInfo::getIndirect(0);
5887 }
5888
5889 // Treat an enum type as its underlying type.
5890 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5891 RetTy = EnumTy->getDecl()->getIntegerType();
5892
5893 return (RetTy->isPromotableIntegerType() ?
5894 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5895}
5896
5897void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005898 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005899 if (!getCXXABI().classifyReturnType(FI))
5900 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005901
5902 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005903 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005904
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005905 for (auto &I : FI.arguments())
5906 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005907}
5908
5909llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5910 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005911 llvm::Type *BP = CGF.Int8PtrTy;
5912 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005913
5914 // Integer arguments are promoted 32-bit on O32 and 64-bit on N32/N64.
5915 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
5916 if (Ty->isIntegerType() &&
5917 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) {
5918 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5919 Ty->isSignedIntegerType());
5920 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005921
5922 CGBuilderTy &Builder = CGF.Builder;
5923 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5924 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005925 int64_t TypeAlign =
5926 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005927 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5928 llvm::Value *AddrTyped;
5929 unsigned PtrWidth = getTarget().getPointerWidth(0);
5930 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5931
5932 if (TypeAlign > MinABIStackAlignInBytes) {
5933 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5934 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5935 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5936 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5937 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5938 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5939 }
5940 else
5941 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5942
5943 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5944 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005945 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5946 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005947 llvm::Value *NextAddr =
5948 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5949 "ap.next");
5950 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5951
5952 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005953}
5954
John McCall943fae92010-05-27 06:19:26 +00005955bool
5956MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5957 llvm::Value *Address) const {
5958 // This information comes from gcc's implementation, which seems to
5959 // as canonical as it gets.
5960
John McCall943fae92010-05-27 06:19:26 +00005961 // Everything on MIPS is 4 bytes. Double-precision FP registers
5962 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005963 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005964
5965 // 0-31 are the general purpose registers, $0 - $31.
5966 // 32-63 are the floating-point registers, $f0 - $f31.
5967 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5968 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005969 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005970
5971 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5972 // They are one bit wide and ignored here.
5973
5974 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5975 // (coprocessor 1 is the FP unit)
5976 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5977 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5978 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005979 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005980 return false;
5981}
5982
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005983//===----------------------------------------------------------------------===//
5984// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5985// Currently subclassed only to implement custom OpenCL C function attribute
5986// handling.
5987//===----------------------------------------------------------------------===//
5988
5989namespace {
5990
5991class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5992public:
5993 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5994 : DefaultTargetCodeGenInfo(CGT) {}
5995
Craig Topper4f12f102014-03-12 06:41:41 +00005996 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5997 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005998};
5999
6000void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
6001 llvm::GlobalValue *GV,
6002 CodeGen::CodeGenModule &M) const {
6003 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6004 if (!FD) return;
6005
6006 llvm::Function *F = cast<llvm::Function>(GV);
6007
David Blaikiebbafb8a2012-03-11 07:00:24 +00006008 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006009 if (FD->hasAttr<OpenCLKernelAttr>()) {
6010 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006011 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006012 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6013 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006014 // Convert the reqd_work_group_size() attributes to metadata.
6015 llvm::LLVMContext &Context = F->getContext();
6016 llvm::NamedMDNode *OpenCLMetadata =
6017 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
6018
6019 SmallVector<llvm::Value*, 5> Operands;
6020 Operands.push_back(F);
6021
Chris Lattnerece04092012-02-07 00:39:47 +00006022 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006023 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00006024 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006025 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00006026 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006027 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006028
6029 // Add a boolean constant operand for "required" (true) or "hint" (false)
6030 // for implementing the work_group_size_hint attr later. Currently
6031 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00006032 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006033 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6034 }
6035 }
6036 }
6037}
6038
6039}
John McCall943fae92010-05-27 06:19:26 +00006040
Tony Linthicum76329bf2011-12-12 21:14:55 +00006041//===----------------------------------------------------------------------===//
6042// Hexagon ABI Implementation
6043//===----------------------------------------------------------------------===//
6044
6045namespace {
6046
6047class HexagonABIInfo : public ABIInfo {
6048
6049
6050public:
6051 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6052
6053private:
6054
6055 ABIArgInfo classifyReturnType(QualType RetTy) const;
6056 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6057
Craig Topper4f12f102014-03-12 06:41:41 +00006058 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006059
Craig Topper4f12f102014-03-12 06:41:41 +00006060 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6061 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006062};
6063
6064class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6065public:
6066 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6067 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6068
Craig Topper4f12f102014-03-12 06:41:41 +00006069 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006070 return 29;
6071 }
6072};
6073
6074}
6075
6076void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006077 if (!getCXXABI().classifyReturnType(FI))
6078 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006079 for (auto &I : FI.arguments())
6080 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006081}
6082
6083ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6084 if (!isAggregateTypeForABI(Ty)) {
6085 // Treat an enum type as its underlying type.
6086 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6087 Ty = EnumTy->getDecl()->getIntegerType();
6088
6089 return (Ty->isPromotableIntegerType() ?
6090 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6091 }
6092
6093 // Ignore empty records.
6094 if (isEmptyRecord(getContext(), Ty, true))
6095 return ABIArgInfo::getIgnore();
6096
Mark Lacey3825e832013-10-06 01:33:34 +00006097 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006098 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006099
6100 uint64_t Size = getContext().getTypeSize(Ty);
6101 if (Size > 64)
6102 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6103 // Pass in the smallest viable integer type.
6104 else if (Size > 32)
6105 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6106 else if (Size > 16)
6107 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6108 else if (Size > 8)
6109 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6110 else
6111 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6112}
6113
6114ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6115 if (RetTy->isVoidType())
6116 return ABIArgInfo::getIgnore();
6117
6118 // Large vector types should be returned via memory.
6119 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6120 return ABIArgInfo::getIndirect(0);
6121
6122 if (!isAggregateTypeForABI(RetTy)) {
6123 // Treat an enum type as its underlying type.
6124 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6125 RetTy = EnumTy->getDecl()->getIntegerType();
6126
6127 return (RetTy->isPromotableIntegerType() ?
6128 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6129 }
6130
Tony Linthicum76329bf2011-12-12 21:14:55 +00006131 if (isEmptyRecord(getContext(), RetTy, true))
6132 return ABIArgInfo::getIgnore();
6133
6134 // Aggregates <= 8 bytes are returned in r0; other aggregates
6135 // are returned indirectly.
6136 uint64_t Size = getContext().getTypeSize(RetTy);
6137 if (Size <= 64) {
6138 // Return in the smallest viable integer type.
6139 if (Size <= 8)
6140 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6141 if (Size <= 16)
6142 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6143 if (Size <= 32)
6144 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6145 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6146 }
6147
6148 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6149}
6150
6151llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006152 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006153 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006154 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006155
6156 CGBuilderTy &Builder = CGF.Builder;
6157 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6158 "ap");
6159 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6160 llvm::Type *PTy =
6161 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6162 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6163
6164 uint64_t Offset =
6165 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6166 llvm::Value *NextAddr =
6167 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6168 "ap.next");
6169 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6170
6171 return AddrTyped;
6172}
6173
6174
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006175//===----------------------------------------------------------------------===//
6176// SPARC v9 ABI Implementation.
6177// Based on the SPARC Compliance Definition version 2.4.1.
6178//
6179// Function arguments a mapped to a nominal "parameter array" and promoted to
6180// registers depending on their type. Each argument occupies 8 or 16 bytes in
6181// the array, structs larger than 16 bytes are passed indirectly.
6182//
6183// One case requires special care:
6184//
6185// struct mixed {
6186// int i;
6187// float f;
6188// };
6189//
6190// When a struct mixed is passed by value, it only occupies 8 bytes in the
6191// parameter array, but the int is passed in an integer register, and the float
6192// is passed in a floating point register. This is represented as two arguments
6193// with the LLVM IR inreg attribute:
6194//
6195// declare void f(i32 inreg %i, float inreg %f)
6196//
6197// The code generator will only allocate 4 bytes from the parameter array for
6198// the inreg arguments. All other arguments are allocated a multiple of 8
6199// bytes.
6200//
6201namespace {
6202class SparcV9ABIInfo : public ABIInfo {
6203public:
6204 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6205
6206private:
6207 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006208 void computeInfo(CGFunctionInfo &FI) const override;
6209 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6210 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006211
6212 // Coercion type builder for structs passed in registers. The coercion type
6213 // serves two purposes:
6214 //
6215 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6216 // in registers.
6217 // 2. Expose aligned floating point elements as first-level elements, so the
6218 // code generator knows to pass them in floating point registers.
6219 //
6220 // We also compute the InReg flag which indicates that the struct contains
6221 // aligned 32-bit floats.
6222 //
6223 struct CoerceBuilder {
6224 llvm::LLVMContext &Context;
6225 const llvm::DataLayout &DL;
6226 SmallVector<llvm::Type*, 8> Elems;
6227 uint64_t Size;
6228 bool InReg;
6229
6230 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6231 : Context(c), DL(dl), Size(0), InReg(false) {}
6232
6233 // Pad Elems with integers until Size is ToSize.
6234 void pad(uint64_t ToSize) {
6235 assert(ToSize >= Size && "Cannot remove elements");
6236 if (ToSize == Size)
6237 return;
6238
6239 // Finish the current 64-bit word.
6240 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6241 if (Aligned > Size && Aligned <= ToSize) {
6242 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6243 Size = Aligned;
6244 }
6245
6246 // Add whole 64-bit words.
6247 while (Size + 64 <= ToSize) {
6248 Elems.push_back(llvm::Type::getInt64Ty(Context));
6249 Size += 64;
6250 }
6251
6252 // Final in-word padding.
6253 if (Size < ToSize) {
6254 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6255 Size = ToSize;
6256 }
6257 }
6258
6259 // Add a floating point element at Offset.
6260 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6261 // Unaligned floats are treated as integers.
6262 if (Offset % Bits)
6263 return;
6264 // The InReg flag is only required if there are any floats < 64 bits.
6265 if (Bits < 64)
6266 InReg = true;
6267 pad(Offset);
6268 Elems.push_back(Ty);
6269 Size = Offset + Bits;
6270 }
6271
6272 // Add a struct type to the coercion type, starting at Offset (in bits).
6273 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6274 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6275 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6276 llvm::Type *ElemTy = StrTy->getElementType(i);
6277 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6278 switch (ElemTy->getTypeID()) {
6279 case llvm::Type::StructTyID:
6280 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6281 break;
6282 case llvm::Type::FloatTyID:
6283 addFloat(ElemOffset, ElemTy, 32);
6284 break;
6285 case llvm::Type::DoubleTyID:
6286 addFloat(ElemOffset, ElemTy, 64);
6287 break;
6288 case llvm::Type::FP128TyID:
6289 addFloat(ElemOffset, ElemTy, 128);
6290 break;
6291 case llvm::Type::PointerTyID:
6292 if (ElemOffset % 64 == 0) {
6293 pad(ElemOffset);
6294 Elems.push_back(ElemTy);
6295 Size += 64;
6296 }
6297 break;
6298 default:
6299 break;
6300 }
6301 }
6302 }
6303
6304 // Check if Ty is a usable substitute for the coercion type.
6305 bool isUsableType(llvm::StructType *Ty) const {
6306 if (Ty->getNumElements() != Elems.size())
6307 return false;
6308 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6309 if (Elems[i] != Ty->getElementType(i))
6310 return false;
6311 return true;
6312 }
6313
6314 // Get the coercion type as a literal struct type.
6315 llvm::Type *getType() const {
6316 if (Elems.size() == 1)
6317 return Elems.front();
6318 else
6319 return llvm::StructType::get(Context, Elems);
6320 }
6321 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006322};
6323} // end anonymous namespace
6324
6325ABIArgInfo
6326SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6327 if (Ty->isVoidType())
6328 return ABIArgInfo::getIgnore();
6329
6330 uint64_t Size = getContext().getTypeSize(Ty);
6331
6332 // Anything too big to fit in registers is passed with an explicit indirect
6333 // pointer / sret pointer.
6334 if (Size > SizeLimit)
6335 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6336
6337 // Treat an enum type as its underlying type.
6338 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6339 Ty = EnumTy->getDecl()->getIntegerType();
6340
6341 // Integer types smaller than a register are extended.
6342 if (Size < 64 && Ty->isIntegerType())
6343 return ABIArgInfo::getExtend();
6344
6345 // Other non-aggregates go in registers.
6346 if (!isAggregateTypeForABI(Ty))
6347 return ABIArgInfo::getDirect();
6348
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006349 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6350 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6351 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6352 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6353
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006354 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006355 // Build a coercion type from the LLVM struct type.
6356 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6357 if (!StrTy)
6358 return ABIArgInfo::getDirect();
6359
6360 CoerceBuilder CB(getVMContext(), getDataLayout());
6361 CB.addStruct(0, StrTy);
6362 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6363
6364 // Try to use the original type for coercion.
6365 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6366
6367 if (CB.InReg)
6368 return ABIArgInfo::getDirectInReg(CoerceTy);
6369 else
6370 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006371}
6372
6373llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6374 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006375 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6376 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6377 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6378 AI.setCoerceToType(ArgTy);
6379
6380 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6381 CGBuilderTy &Builder = CGF.Builder;
6382 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6383 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6384 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6385 llvm::Value *ArgAddr;
6386 unsigned Stride;
6387
6388 switch (AI.getKind()) {
6389 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006390 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006391 llvm_unreachable("Unsupported ABI kind for va_arg");
6392
6393 case ABIArgInfo::Extend:
6394 Stride = 8;
6395 ArgAddr = Builder
6396 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6397 "extend");
6398 break;
6399
6400 case ABIArgInfo::Direct:
6401 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6402 ArgAddr = Addr;
6403 break;
6404
6405 case ABIArgInfo::Indirect:
6406 Stride = 8;
6407 ArgAddr = Builder.CreateBitCast(Addr,
6408 llvm::PointerType::getUnqual(ArgPtrTy),
6409 "indirect");
6410 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6411 break;
6412
6413 case ABIArgInfo::Ignore:
6414 return llvm::UndefValue::get(ArgPtrTy);
6415 }
6416
6417 // Update VAList.
6418 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6419 Builder.CreateStore(Addr, VAListAddrAsBPP);
6420
6421 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006422}
6423
6424void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6425 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006426 for (auto &I : FI.arguments())
6427 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006428}
6429
6430namespace {
6431class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6432public:
6433 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6434 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006435
Craig Topper4f12f102014-03-12 06:41:41 +00006436 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006437 return 14;
6438 }
6439
6440 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006441 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006442};
6443} // end anonymous namespace
6444
Roman Divackyf02c9942014-02-24 18:46:27 +00006445bool
6446SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6447 llvm::Value *Address) const {
6448 // This is calculated from the LLVM and GCC tables and verified
6449 // against gcc output. AFAIK all ABIs use the same encoding.
6450
6451 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6452
6453 llvm::IntegerType *i8 = CGF.Int8Ty;
6454 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6455 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6456
6457 // 0-31: the 8-byte general-purpose registers
6458 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6459
6460 // 32-63: f0-31, the 4-byte floating-point registers
6461 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6462
6463 // Y = 64
6464 // PSR = 65
6465 // WIM = 66
6466 // TBR = 67
6467 // PC = 68
6468 // NPC = 69
6469 // FSR = 70
6470 // CSR = 71
6471 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6472
6473 // 72-87: d0-15, the 8-byte floating-point registers
6474 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6475
6476 return false;
6477}
6478
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006479
Robert Lytton0e076492013-08-13 09:43:10 +00006480//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006481// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006482//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006483
Robert Lytton0e076492013-08-13 09:43:10 +00006484namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006485
6486/// A SmallStringEnc instance is used to build up the TypeString by passing
6487/// it by reference between functions that append to it.
6488typedef llvm::SmallString<128> SmallStringEnc;
6489
6490/// TypeStringCache caches the meta encodings of Types.
6491///
6492/// The reason for caching TypeStrings is two fold:
6493/// 1. To cache a type's encoding for later uses;
6494/// 2. As a means to break recursive member type inclusion.
6495///
6496/// A cache Entry can have a Status of:
6497/// NonRecursive: The type encoding is not recursive;
6498/// Recursive: The type encoding is recursive;
6499/// Incomplete: An incomplete TypeString;
6500/// IncompleteUsed: An incomplete TypeString that has been used in a
6501/// Recursive type encoding.
6502///
6503/// A NonRecursive entry will have all of its sub-members expanded as fully
6504/// as possible. Whilst it may contain types which are recursive, the type
6505/// itself is not recursive and thus its encoding may be safely used whenever
6506/// the type is encountered.
6507///
6508/// A Recursive entry will have all of its sub-members expanded as fully as
6509/// possible. The type itself is recursive and it may contain other types which
6510/// are recursive. The Recursive encoding must not be used during the expansion
6511/// of a recursive type's recursive branch. For simplicity the code uses
6512/// IncompleteCount to reject all usage of Recursive encodings for member types.
6513///
6514/// An Incomplete entry is always a RecordType and only encodes its
6515/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6516/// are placed into the cache during type expansion as a means to identify and
6517/// handle recursive inclusion of types as sub-members. If there is recursion
6518/// the entry becomes IncompleteUsed.
6519///
6520/// During the expansion of a RecordType's members:
6521///
6522/// If the cache contains a NonRecursive encoding for the member type, the
6523/// cached encoding is used;
6524///
6525/// If the cache contains a Recursive encoding for the member type, the
6526/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6527///
6528/// If the member is a RecordType, an Incomplete encoding is placed into the
6529/// cache to break potential recursive inclusion of itself as a sub-member;
6530///
6531/// Once a member RecordType has been expanded, its temporary incomplete
6532/// entry is removed from the cache. If a Recursive encoding was swapped out
6533/// it is swapped back in;
6534///
6535/// If an incomplete entry is used to expand a sub-member, the incomplete
6536/// entry is marked as IncompleteUsed. The cache keeps count of how many
6537/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6538///
6539/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6540/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6541/// Else the member is part of a recursive type and thus the recursion has
6542/// been exited too soon for the encoding to be correct for the member.
6543///
6544class TypeStringCache {
6545 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6546 struct Entry {
6547 std::string Str; // The encoded TypeString for the type.
6548 enum Status State; // Information about the encoding in 'Str'.
6549 std::string Swapped; // A temporary place holder for a Recursive encoding
6550 // during the expansion of RecordType's members.
6551 };
6552 std::map<const IdentifierInfo *, struct Entry> Map;
6553 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6554 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6555public:
Robert Lyttond263f142014-05-06 09:38:54 +00006556 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006557 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6558 bool removeIncomplete(const IdentifierInfo *ID);
6559 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6560 bool IsRecursive);
6561 StringRef lookupStr(const IdentifierInfo *ID);
6562};
6563
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006564/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006565/// FieldEncoding is a helper for this ordering process.
6566class FieldEncoding {
6567 bool HasName;
6568 std::string Enc;
6569public:
6570 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6571 StringRef str() {return Enc.c_str();};
6572 bool operator<(const FieldEncoding &rhs) const {
6573 if (HasName != rhs.HasName) return HasName;
6574 return Enc < rhs.Enc;
6575 }
6576};
6577
Robert Lytton7d1db152013-08-19 09:46:39 +00006578class XCoreABIInfo : public DefaultABIInfo {
6579public:
6580 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006581 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6582 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006583};
6584
Robert Lyttond21e2d72014-03-03 13:45:29 +00006585class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006586 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006587public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006588 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006589 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006590 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6591 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006592};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006593
Robert Lytton2d196952013-10-11 10:29:34 +00006594} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006595
Robert Lytton7d1db152013-08-19 09:46:39 +00006596llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6597 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006598 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006599
Robert Lytton2d196952013-10-11 10:29:34 +00006600 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006601 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6602 CGF.Int8PtrPtrTy);
6603 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006604
Robert Lytton2d196952013-10-11 10:29:34 +00006605 // Handle the argument.
6606 ABIArgInfo AI = classifyArgumentType(Ty);
6607 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6608 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6609 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006610 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006611 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006612 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006613 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006614 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006615 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006616 llvm_unreachable("Unsupported ABI kind for va_arg");
6617 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006618 Val = llvm::UndefValue::get(ArgPtrTy);
6619 ArgSize = 0;
6620 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006621 case ABIArgInfo::Extend:
6622 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006623 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6624 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6625 if (ArgSize < 4)
6626 ArgSize = 4;
6627 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006628 case ABIArgInfo::Indirect:
6629 llvm::Value *ArgAddr;
6630 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6631 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006632 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6633 ArgSize = 4;
6634 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006635 }
Robert Lytton2d196952013-10-11 10:29:34 +00006636
6637 // Increment the VAList.
6638 if (ArgSize) {
6639 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6640 Builder.CreateStore(APN, VAListAddrAsBPP);
6641 }
6642 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006643}
Robert Lytton0e076492013-08-13 09:43:10 +00006644
Robert Lytton844aeeb2014-05-02 09:33:20 +00006645/// During the expansion of a RecordType, an incomplete TypeString is placed
6646/// into the cache as a means to identify and break recursion.
6647/// If there is a Recursive encoding in the cache, it is swapped out and will
6648/// be reinserted by removeIncomplete().
6649/// All other types of encoding should have been used rather than arriving here.
6650void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6651 std::string StubEnc) {
6652 if (!ID)
6653 return;
6654 Entry &E = Map[ID];
6655 assert( (E.Str.empty() || E.State == Recursive) &&
6656 "Incorrectly use of addIncomplete");
6657 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6658 E.Swapped.swap(E.Str); // swap out the Recursive
6659 E.Str.swap(StubEnc);
6660 E.State = Incomplete;
6661 ++IncompleteCount;
6662}
6663
6664/// Once the RecordType has been expanded, the temporary incomplete TypeString
6665/// must be removed from the cache.
6666/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6667/// Returns true if the RecordType was defined recursively.
6668bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6669 if (!ID)
6670 return false;
6671 auto I = Map.find(ID);
6672 assert(I != Map.end() && "Entry not present");
6673 Entry &E = I->second;
6674 assert( (E.State == Incomplete ||
6675 E.State == IncompleteUsed) &&
6676 "Entry must be an incomplete type");
6677 bool IsRecursive = false;
6678 if (E.State == IncompleteUsed) {
6679 // We made use of our Incomplete encoding, thus we are recursive.
6680 IsRecursive = true;
6681 --IncompleteUsedCount;
6682 }
6683 if (E.Swapped.empty())
6684 Map.erase(I);
6685 else {
6686 // Swap the Recursive back.
6687 E.Swapped.swap(E.Str);
6688 E.Swapped.clear();
6689 E.State = Recursive;
6690 }
6691 --IncompleteCount;
6692 return IsRecursive;
6693}
6694
6695/// Add the encoded TypeString to the cache only if it is NonRecursive or
6696/// Recursive (viz: all sub-members were expanded as fully as possible).
6697void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6698 bool IsRecursive) {
6699 if (!ID || IncompleteUsedCount)
6700 return; // No key or it is is an incomplete sub-type so don't add.
6701 Entry &E = Map[ID];
6702 if (IsRecursive && !E.Str.empty()) {
6703 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6704 "This is not the same Recursive entry");
6705 // The parent container was not recursive after all, so we could have used
6706 // this Recursive sub-member entry after all, but we assumed the worse when
6707 // we started viz: IncompleteCount!=0.
6708 return;
6709 }
6710 assert(E.Str.empty() && "Entry already present");
6711 E.Str = Str.str();
6712 E.State = IsRecursive? Recursive : NonRecursive;
6713}
6714
6715/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6716/// are recursively expanding a type (IncompleteCount != 0) and the cached
6717/// encoding is Recursive, return an empty StringRef.
6718StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6719 if (!ID)
6720 return StringRef(); // We have no key.
6721 auto I = Map.find(ID);
6722 if (I == Map.end())
6723 return StringRef(); // We have no encoding.
6724 Entry &E = I->second;
6725 if (E.State == Recursive && IncompleteCount)
6726 return StringRef(); // We don't use Recursive encodings for member types.
6727
6728 if (E.State == Incomplete) {
6729 // The incomplete type is being used to break out of recursion.
6730 E.State = IncompleteUsed;
6731 ++IncompleteUsedCount;
6732 }
6733 return E.Str.c_str();
6734}
6735
6736/// The XCore ABI includes a type information section that communicates symbol
6737/// type information to the linker. The linker uses this information to verify
6738/// safety/correctness of things such as array bound and pointers et al.
6739/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6740/// This type information (TypeString) is emitted into meta data for all global
6741/// symbols: definitions, declarations, functions & variables.
6742///
6743/// The TypeString carries type, qualifier, name, size & value details.
6744/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6745/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6746/// The output is tested by test/CodeGen/xcore-stringtype.c.
6747///
6748static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6749 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6750
6751/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6752void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6753 CodeGen::CodeGenModule &CGM) const {
6754 SmallStringEnc Enc;
6755 if (getTypeString(Enc, D, CGM, TSC)) {
6756 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6757 llvm::SmallVector<llvm::Value *, 2> MDVals;
6758 MDVals.push_back(GV);
6759 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6760 llvm::NamedMDNode *MD =
6761 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6762 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6763 }
6764}
6765
6766static bool appendType(SmallStringEnc &Enc, QualType QType,
6767 const CodeGen::CodeGenModule &CGM,
6768 TypeStringCache &TSC);
6769
6770/// Helper function for appendRecordType().
6771/// Builds a SmallVector containing the encoded field types in declaration order.
6772static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6773 const RecordDecl *RD,
6774 const CodeGen::CodeGenModule &CGM,
6775 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006776 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006777 SmallStringEnc Enc;
6778 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006779 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006780 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006781 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006782 Enc += "b(";
6783 llvm::raw_svector_ostream OS(Enc);
6784 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006785 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006786 OS.flush();
6787 Enc += ':';
6788 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006789 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006790 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006791 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006792 Enc += ')';
6793 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006794 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006795 }
6796 return true;
6797}
6798
6799/// Appends structure and union types to Enc and adds encoding to cache.
6800/// Recursively calls appendType (via extractFieldType) for each field.
6801/// Union types have their fields ordered according to the ABI.
6802static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6803 const CodeGen::CodeGenModule &CGM,
6804 TypeStringCache &TSC, const IdentifierInfo *ID) {
6805 // Append the cached TypeString if we have one.
6806 StringRef TypeString = TSC.lookupStr(ID);
6807 if (!TypeString.empty()) {
6808 Enc += TypeString;
6809 return true;
6810 }
6811
6812 // Start to emit an incomplete TypeString.
6813 size_t Start = Enc.size();
6814 Enc += (RT->isUnionType()? 'u' : 's');
6815 Enc += '(';
6816 if (ID)
6817 Enc += ID->getName();
6818 Enc += "){";
6819
6820 // We collect all encoded fields and order as necessary.
6821 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006822 const RecordDecl *RD = RT->getDecl()->getDefinition();
6823 if (RD && !RD->field_empty()) {
6824 // An incomplete TypeString stub is placed in the cache for this RecordType
6825 // so that recursive calls to this RecordType will use it whilst building a
6826 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006827 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006828 std::string StubEnc(Enc.substr(Start).str());
6829 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6830 TSC.addIncomplete(ID, std::move(StubEnc));
6831 if (!extractFieldType(FE, RD, CGM, TSC)) {
6832 (void) TSC.removeIncomplete(ID);
6833 return false;
6834 }
6835 IsRecursive = TSC.removeIncomplete(ID);
6836 // The ABI requires unions to be sorted but not structures.
6837 // See FieldEncoding::operator< for sort algorithm.
6838 if (RT->isUnionType())
6839 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006840 // We can now complete the TypeString.
6841 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006842 for (unsigned I = 0; I != E; ++I) {
6843 if (I)
6844 Enc += ',';
6845 Enc += FE[I].str();
6846 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006847 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006848 Enc += '}';
6849 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6850 return true;
6851}
6852
6853/// Appends enum types to Enc and adds the encoding to the cache.
6854static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6855 TypeStringCache &TSC,
6856 const IdentifierInfo *ID) {
6857 // Append the cached TypeString if we have one.
6858 StringRef TypeString = TSC.lookupStr(ID);
6859 if (!TypeString.empty()) {
6860 Enc += TypeString;
6861 return true;
6862 }
6863
6864 size_t Start = Enc.size();
6865 Enc += "e(";
6866 if (ID)
6867 Enc += ID->getName();
6868 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006869
6870 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006871 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006872 SmallVector<FieldEncoding, 16> FE;
6873 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6874 ++I) {
6875 SmallStringEnc EnumEnc;
6876 EnumEnc += "m(";
6877 EnumEnc += I->getName();
6878 EnumEnc += "){";
6879 I->getInitVal().toString(EnumEnc);
6880 EnumEnc += '}';
6881 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6882 }
6883 std::sort(FE.begin(), FE.end());
6884 unsigned E = FE.size();
6885 for (unsigned I = 0; I != E; ++I) {
6886 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006887 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006888 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006889 }
6890 }
6891 Enc += '}';
6892 TSC.addIfComplete(ID, Enc.substr(Start), false);
6893 return true;
6894}
6895
6896/// Appends type's qualifier to Enc.
6897/// This is done prior to appending the type's encoding.
6898static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6899 // Qualifiers are emitted in alphabetical order.
6900 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6901 int Lookup = 0;
6902 if (QT.isConstQualified())
6903 Lookup += 1<<0;
6904 if (QT.isRestrictQualified())
6905 Lookup += 1<<1;
6906 if (QT.isVolatileQualified())
6907 Lookup += 1<<2;
6908 Enc += Table[Lookup];
6909}
6910
6911/// Appends built-in types to Enc.
6912static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6913 const char *EncType;
6914 switch (BT->getKind()) {
6915 case BuiltinType::Void:
6916 EncType = "0";
6917 break;
6918 case BuiltinType::Bool:
6919 EncType = "b";
6920 break;
6921 case BuiltinType::Char_U:
6922 EncType = "uc";
6923 break;
6924 case BuiltinType::UChar:
6925 EncType = "uc";
6926 break;
6927 case BuiltinType::SChar:
6928 EncType = "sc";
6929 break;
6930 case BuiltinType::UShort:
6931 EncType = "us";
6932 break;
6933 case BuiltinType::Short:
6934 EncType = "ss";
6935 break;
6936 case BuiltinType::UInt:
6937 EncType = "ui";
6938 break;
6939 case BuiltinType::Int:
6940 EncType = "si";
6941 break;
6942 case BuiltinType::ULong:
6943 EncType = "ul";
6944 break;
6945 case BuiltinType::Long:
6946 EncType = "sl";
6947 break;
6948 case BuiltinType::ULongLong:
6949 EncType = "ull";
6950 break;
6951 case BuiltinType::LongLong:
6952 EncType = "sll";
6953 break;
6954 case BuiltinType::Float:
6955 EncType = "ft";
6956 break;
6957 case BuiltinType::Double:
6958 EncType = "d";
6959 break;
6960 case BuiltinType::LongDouble:
6961 EncType = "ld";
6962 break;
6963 default:
6964 return false;
6965 }
6966 Enc += EncType;
6967 return true;
6968}
6969
6970/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6971static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6972 const CodeGen::CodeGenModule &CGM,
6973 TypeStringCache &TSC) {
6974 Enc += "p(";
6975 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6976 return false;
6977 Enc += ')';
6978 return true;
6979}
6980
6981/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006982static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6983 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006984 const CodeGen::CodeGenModule &CGM,
6985 TypeStringCache &TSC, StringRef NoSizeEnc) {
6986 if (AT->getSizeModifier() != ArrayType::Normal)
6987 return false;
6988 Enc += "a(";
6989 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6990 CAT->getSize().toStringUnsigned(Enc);
6991 else
6992 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6993 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006994 // The Qualifiers should be attached to the type rather than the array.
6995 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006996 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6997 return false;
6998 Enc += ')';
6999 return true;
7000}
7001
7002/// Appends a function encoding to Enc, calling appendType for the return type
7003/// and the arguments.
7004static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7005 const CodeGen::CodeGenModule &CGM,
7006 TypeStringCache &TSC) {
7007 Enc += "f{";
7008 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7009 return false;
7010 Enc += "}(";
7011 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7012 // N.B. we are only interested in the adjusted param types.
7013 auto I = FPT->param_type_begin();
7014 auto E = FPT->param_type_end();
7015 if (I != E) {
7016 do {
7017 if (!appendType(Enc, *I, CGM, TSC))
7018 return false;
7019 ++I;
7020 if (I != E)
7021 Enc += ',';
7022 } while (I != E);
7023 if (FPT->isVariadic())
7024 Enc += ",va";
7025 } else {
7026 if (FPT->isVariadic())
7027 Enc += "va";
7028 else
7029 Enc += '0';
7030 }
7031 }
7032 Enc += ')';
7033 return true;
7034}
7035
7036/// Handles the type's qualifier before dispatching a call to handle specific
7037/// type encodings.
7038static bool appendType(SmallStringEnc &Enc, QualType QType,
7039 const CodeGen::CodeGenModule &CGM,
7040 TypeStringCache &TSC) {
7041
7042 QualType QT = QType.getCanonicalType();
7043
Robert Lytton6adb20f2014-06-05 09:06:21 +00007044 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7045 // The Qualifiers should be attached to the type rather than the array.
7046 // Thus we don't call appendQualifier() here.
7047 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7048
Robert Lytton844aeeb2014-05-02 09:33:20 +00007049 appendQualifier(Enc, QT);
7050
7051 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7052 return appendBuiltinType(Enc, BT);
7053
Robert Lytton844aeeb2014-05-02 09:33:20 +00007054 if (const PointerType *PT = QT->getAs<PointerType>())
7055 return appendPointerType(Enc, PT, CGM, TSC);
7056
7057 if (const EnumType *ET = QT->getAs<EnumType>())
7058 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7059
7060 if (const RecordType *RT = QT->getAsStructureType())
7061 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7062
7063 if (const RecordType *RT = QT->getAsUnionType())
7064 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7065
7066 if (const FunctionType *FT = QT->getAs<FunctionType>())
7067 return appendFunctionType(Enc, FT, CGM, TSC);
7068
7069 return false;
7070}
7071
7072static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7073 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7074 if (!D)
7075 return false;
7076
7077 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7078 if (FD->getLanguageLinkage() != CLanguageLinkage)
7079 return false;
7080 return appendType(Enc, FD->getType(), CGM, TSC);
7081 }
7082
7083 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7084 if (VD->getLanguageLinkage() != CLanguageLinkage)
7085 return false;
7086 QualType QT = VD->getType().getCanonicalType();
7087 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7088 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007089 // The Qualifiers should be attached to the type rather than the array.
7090 // Thus we don't call appendQualifier() here.
7091 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007092 }
7093 return appendType(Enc, QT, CGM, TSC);
7094 }
7095 return false;
7096}
7097
7098
Robert Lytton0e076492013-08-13 09:43:10 +00007099//===----------------------------------------------------------------------===//
7100// Driver code
7101//===----------------------------------------------------------------------===//
7102
Rafael Espindola9f834732014-09-19 01:54:22 +00007103const llvm::Triple &CodeGenModule::getTriple() const {
7104 return getTarget().getTriple();
7105}
7106
7107bool CodeGenModule::supportsCOMDAT() const {
7108 return !getTriple().isOSBinFormatMachO();
7109}
7110
Chris Lattner2b037972010-07-29 02:01:43 +00007111const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007112 if (TheTargetCodeGenInfo)
7113 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007114
John McCallc8e01702013-04-16 22:48:15 +00007115 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007116 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007117 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007118 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007119
Derek Schuff09338a22012-09-06 17:37:28 +00007120 case llvm::Triple::le32:
7121 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007122 case llvm::Triple::mips:
7123 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007124 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7125
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007126 case llvm::Triple::mips64:
7127 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007128 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7129
Tim Northover25e8a672014-05-24 12:51:25 +00007130 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007131 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007132 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007133 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007134 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007135
Tim Northover573cbee2014-05-24 12:52:07 +00007136 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007137 }
7138
Daniel Dunbard59655c2009-09-12 00:59:49 +00007139 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007140 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007141 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007142 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007143 {
7144 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007145 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007146 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007147 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007148 (CodeGenOpts.FloatABI != "soft" &&
7149 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007150 Kind = ARMABIInfo::AAPCS_VFP;
7151
Derek Schuffa2020962012-10-16 22:30:41 +00007152 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00007153 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00007154 return *(TheTargetCodeGenInfo =
7155 new NaClARMTargetCodeGenInfo(Types, Kind));
7156 default:
7157 return *(TheTargetCodeGenInfo =
7158 new ARMTargetCodeGenInfo(Types, Kind));
7159 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007160 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007161
John McCallea8d8bb2010-03-11 00:10:12 +00007162 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007163 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007164 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007165 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007166 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007167 if (getTarget().getABI() == "elfv2")
7168 Kind = PPC64_SVR4_ABIInfo::ELFv2;
7169
Ulrich Weigandb7122372014-07-21 00:48:09 +00007170 return *(TheTargetCodeGenInfo =
7171 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7172 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007173 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007174 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007175 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007176 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007177 if (getTarget().getABI() == "elfv1")
7178 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7179
Ulrich Weigandb7122372014-07-21 00:48:09 +00007180 return *(TheTargetCodeGenInfo =
7181 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7182 }
John McCallea8d8bb2010-03-11 00:10:12 +00007183
Peter Collingbournec947aae2012-05-20 23:28:41 +00007184 case llvm::Triple::nvptx:
7185 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007186 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007187
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007188 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007189 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007190
Ulrich Weigand47445072013-05-06 16:26:41 +00007191 case llvm::Triple::systemz:
7192 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7193
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007194 case llvm::Triple::tce:
7195 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7196
Eli Friedman33465822011-07-08 23:31:17 +00007197 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007198 bool IsDarwinVectorABI = Triple.isOSDarwin();
7199 bool IsSmallStructInRegABI =
7200 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007201 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007202
John McCall1fe2a8c2013-06-18 02:46:29 +00007203 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007204 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007205 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007206 IsDarwinVectorABI, IsSmallStructInRegABI,
7207 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007208 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007209 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007210 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007211 new X86_32TargetCodeGenInfo(Types,
7212 IsDarwinVectorABI, IsSmallStructInRegABI,
7213 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007214 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007215 }
Eli Friedman33465822011-07-08 23:31:17 +00007216 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007217
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007218 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007219 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007220
Chris Lattner04dc9572010-08-31 16:44:54 +00007221 switch (Triple.getOS()) {
7222 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007223 return *(TheTargetCodeGenInfo =
7224 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Benderskyd7c92032012-12-04 18:38:10 +00007225 case llvm::Triple::NaCl:
Alexander Musman09184fe2014-09-30 05:29:28 +00007226 return *(TheTargetCodeGenInfo =
7227 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007228 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007229 return *(TheTargetCodeGenInfo =
7230 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007231 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007232 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007233 case llvm::Triple::hexagon:
7234 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007235 case llvm::Triple::sparcv9:
7236 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007237 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007238 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007239 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007240}