blob: 117767d0b3659c6f8114b10920044a688b230041 [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"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#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
Peter Collingbournef7706832014-12-12 23:41:25 +00001148 // The chain argument effectively gives us another free register.
1149 if (FI.isChainCall())
1150 ++State.FreeRegs;
1151
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001152 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001153 for (auto &I : FI.arguments()) {
1154 I.info = classifyArgumentType(I.type, State);
1155 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001156 }
1157
1158 // If we needed to use inalloca for any argument, do a second pass and rewrite
1159 // all the memory arguments to use inalloca.
1160 if (UsedInAlloca)
1161 rewriteWithInAlloca(FI);
1162}
1163
1164void
1165X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1166 unsigned &StackOffset,
1167 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001168 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1169 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1170 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1171 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1172
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001173 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1174 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001175 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001176 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001177 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001178 unsigned NumBytes = StackOffset - OldOffset;
1179 assert(NumBytes);
1180 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1181 Ty = llvm::ArrayType::get(Ty, NumBytes);
1182 FrameFields.push_back(Ty);
1183 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001184}
1185
Reid Kleckner852361d2014-07-26 00:12:26 +00001186static bool isArgInAlloca(const ABIArgInfo &Info) {
1187 // Leave ignored and inreg arguments alone.
1188 switch (Info.getKind()) {
1189 case ABIArgInfo::InAlloca:
1190 return true;
1191 case ABIArgInfo::Indirect:
1192 assert(Info.getIndirectByVal());
1193 return true;
1194 case ABIArgInfo::Ignore:
1195 return false;
1196 case ABIArgInfo::Direct:
1197 case ABIArgInfo::Extend:
1198 case ABIArgInfo::Expand:
1199 if (Info.getInReg())
1200 return false;
1201 return true;
1202 }
1203 llvm_unreachable("invalid enum");
1204}
1205
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001206void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1207 assert(IsWin32StructABI && "inalloca only supported on win32");
1208
1209 // Build a packed struct type for all of the arguments in memory.
1210 SmallVector<llvm::Type *, 6> FrameFields;
1211
1212 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001213 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1214
1215 // Put 'this' into the struct before 'sret', if necessary.
1216 bool IsThisCall =
1217 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1218 ABIArgInfo &Ret = FI.getReturnInfo();
1219 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1220 isArgInAlloca(I->info)) {
1221 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1222 ++I;
1223 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001224
1225 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001226 if (Ret.isIndirect() && !Ret.getInReg()) {
1227 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1228 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001229 // On Windows, the hidden sret parameter is always returned in eax.
1230 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001231 }
1232
1233 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001234 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001235 ++I;
1236
1237 // Put arguments passed in memory into the struct.
1238 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001239 if (isArgInAlloca(I->info))
1240 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001241 }
1242
1243 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1244 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001245}
1246
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1248 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001249 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001250
1251 CGBuilderTy &Builder = CGF.Builder;
1252 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1253 "ap");
1254 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001255
1256 // Compute if the address needs to be aligned
1257 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1258 Align = getTypeStackAlignInBytes(Ty, Align);
1259 Align = std::max(Align, 4U);
1260 if (Align > 4) {
1261 // addr = (addr + align - 1) & -align;
1262 llvm::Value *Offset =
1263 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1264 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1265 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1266 CGF.Int32Ty);
1267 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1268 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1269 Addr->getType(),
1270 "ap.cur.aligned");
1271 }
1272
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001273 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001274 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1276
1277 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001278 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001279 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001280 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001281 "ap.next");
1282 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1283
1284 return AddrTyped;
1285}
1286
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001287bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1288 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1289 assert(Triple.getArch() == llvm::Triple::x86);
1290
1291 switch (Opts.getStructReturnConvention()) {
1292 case CodeGenOptions::SRCK_Default:
1293 break;
1294 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1295 return false;
1296 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1297 return true;
1298 }
1299
1300 if (Triple.isOSDarwin())
1301 return true;
1302
1303 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001304 case llvm::Triple::DragonFly:
1305 case llvm::Triple::FreeBSD:
1306 case llvm::Triple::OpenBSD:
1307 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001308 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001309 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001310 default:
1311 return false;
1312 }
1313}
1314
Charles Davis4ea31ab2010-02-13 15:54:06 +00001315void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1316 llvm::GlobalValue *GV,
1317 CodeGen::CodeGenModule &CGM) const {
1318 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1319 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1320 // Get the LLVM function.
1321 llvm::Function *Fn = cast<llvm::Function>(GV);
1322
1323 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001324 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001325 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001326 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1327 llvm::AttributeSet::get(CGM.getLLVMContext(),
1328 llvm::AttributeSet::FunctionIndex,
1329 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001330 }
1331 }
1332}
1333
John McCallbeec5a02010-03-06 00:35:14 +00001334bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1335 CodeGen::CodeGenFunction &CGF,
1336 llvm::Value *Address) const {
1337 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001338
Chris Lattnerece04092012-02-07 00:39:47 +00001339 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001340
John McCallbeec5a02010-03-06 00:35:14 +00001341 // 0-7 are the eight integer registers; the order is different
1342 // on Darwin (for EH), but the range is the same.
1343 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001344 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001345
John McCallc8e01702013-04-16 22:48:15 +00001346 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001347 // 12-16 are st(0..4). Not sure why we stop at 4.
1348 // These have size 16, which is sizeof(long double) on
1349 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001350 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001351 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001352
John McCallbeec5a02010-03-06 00:35:14 +00001353 } else {
1354 // 9 is %eflags, which doesn't get a size on Darwin for some
1355 // reason.
1356 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1357
1358 // 11-16 are st(0..5). Not sure why we stop at 5.
1359 // These have size 12, which is sizeof(long double) on
1360 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001361 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001362 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1363 }
John McCallbeec5a02010-03-06 00:35:14 +00001364
1365 return false;
1366}
1367
Chris Lattner0cf24192010-06-28 20:05:43 +00001368//===----------------------------------------------------------------------===//
1369// X86-64 ABI Implementation
1370//===----------------------------------------------------------------------===//
1371
1372
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001373namespace {
1374/// X86_64ABIInfo - The X86_64 ABI information.
1375class X86_64ABIInfo : public ABIInfo {
1376 enum Class {
1377 Integer = 0,
1378 SSE,
1379 SSEUp,
1380 X87,
1381 X87Up,
1382 ComplexX87,
1383 NoClass,
1384 Memory
1385 };
1386
1387 /// merge - Implement the X86_64 ABI merging algorithm.
1388 ///
1389 /// Merge an accumulating classification \arg Accum with a field
1390 /// classification \arg Field.
1391 ///
1392 /// \param Accum - The accumulating classification. This should
1393 /// always be either NoClass or the result of a previous merge
1394 /// call. In addition, this should never be Memory (the caller
1395 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001396 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001397
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001398 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1399 ///
1400 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1401 /// final MEMORY or SSE classes when necessary.
1402 ///
1403 /// \param AggregateSize - The size of the current aggregate in
1404 /// the classification process.
1405 ///
1406 /// \param Lo - The classification for the parts of the type
1407 /// residing in the low word of the containing object.
1408 ///
1409 /// \param Hi - The classification for the parts of the type
1410 /// residing in the higher words of the containing object.
1411 ///
1412 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1413
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001414 /// classify - Determine the x86_64 register classes in which the
1415 /// given type T should be passed.
1416 ///
1417 /// \param Lo - The classification for the parts of the type
1418 /// residing in the low word of the containing object.
1419 ///
1420 /// \param Hi - The classification for the parts of the type
1421 /// residing in the high word of the containing object.
1422 ///
1423 /// \param OffsetBase - The bit offset of this type in the
1424 /// containing object. Some parameters are classified different
1425 /// depending on whether they straddle an eightbyte boundary.
1426 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001427 /// \param isNamedArg - Whether the argument in question is a "named"
1428 /// argument, as used in AMD64-ABI 3.5.7.
1429 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001430 /// If a word is unused its result will be NoClass; if a type should
1431 /// be passed in Memory then at least the classification of \arg Lo
1432 /// will be Memory.
1433 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001434 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001435 ///
1436 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1437 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001438 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1439 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001440
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001441 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001442 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1443 unsigned IROffset, QualType SourceTy,
1444 unsigned SourceOffset) const;
1445 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1446 unsigned IROffset, QualType SourceTy,
1447 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001448
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001449 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001450 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001451 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001452
1453 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001454 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001455 ///
1456 /// \param freeIntRegs - The number of free integer registers remaining
1457 /// available.
1458 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001459
Chris Lattner458b2aa2010-07-29 02:16:43 +00001460 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001461
Bill Wendling5cd41c42010-10-18 03:41:31 +00001462 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001463 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001464 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001465 unsigned &neededSSE,
1466 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001467
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001468 bool IsIllegalVectorType(QualType Ty) const;
1469
John McCalle0fda732011-04-21 01:20:55 +00001470 /// The 0.98 ABI revision clarified a lot of ambiguities,
1471 /// unfortunately in ways that were not always consistent with
1472 /// certain previous compilers. In particular, platforms which
1473 /// required strict binary compatibility with older versions of GCC
1474 /// may need to exempt themselves.
1475 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001476 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001477 }
1478
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001479 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001480 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1481 // 64-bit hardware.
1482 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001483
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001484public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001485 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001486 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001487 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001488 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001489
John McCalla729c622012-02-17 03:33:10 +00001490 bool isPassedUsingAVXType(QualType type) const {
1491 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001492 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001493 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1494 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001495 if (info.isDirect()) {
1496 llvm::Type *ty = info.getCoerceToType();
1497 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1498 return (vectorTy->getBitWidth() > 128);
1499 }
1500 return false;
1501 }
1502
Craig Topper4f12f102014-03-12 06:41:41 +00001503 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001504
Craig Topper4f12f102014-03-12 06:41:41 +00001505 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1506 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001507};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001508
Chris Lattner04dc9572010-08-31 16:44:54 +00001509/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001510class WinX86_64ABIInfo : public ABIInfo {
1511
Reid Kleckner80944df2014-10-31 22:00:51 +00001512 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1513 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001514
Chris Lattner04dc9572010-08-31 16:44:54 +00001515public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001516 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1517
Craig Topper4f12f102014-03-12 06:41:41 +00001518 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001519
Craig Topper4f12f102014-03-12 06:41:41 +00001520 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1521 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001522
1523 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1524 // FIXME: Assumes vectorcall is in use.
1525 return isX86VectorTypeForVectorCall(getContext(), Ty);
1526 }
1527
1528 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1529 uint64_t NumMembers) const override {
1530 // FIXME: Assumes vectorcall is in use.
1531 return isX86VectorCallAggregateSmallEnough(NumMembers);
1532 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001533};
1534
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001535class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001536 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001537public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001538 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001539 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001540
John McCalla729c622012-02-17 03:33:10 +00001541 const X86_64ABIInfo &getABIInfo() const {
1542 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1543 }
1544
Craig Topper4f12f102014-03-12 06:41:41 +00001545 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001546 return 7;
1547 }
1548
1549 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001550 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001551 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001552
John McCall943fae92010-05-27 06:19:26 +00001553 // 0-15 are the 16 integer registers.
1554 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001555 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001556 return false;
1557 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001558
Jay Foad7c57be32011-07-11 09:56:20 +00001559 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001560 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001561 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001562 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1563 }
1564
John McCalla729c622012-02-17 03:33:10 +00001565 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001566 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001567 // The default CC on x86-64 sets %al to the number of SSA
1568 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001569 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001570 // that when AVX types are involved: the ABI explicitly states it is
1571 // undefined, and it doesn't work in practice because of how the ABI
1572 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001573 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001574 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001575 for (CallArgList::const_iterator
1576 it = args.begin(), ie = args.end(); it != ie; ++it) {
1577 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1578 HasAVXType = true;
1579 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001580 }
1581 }
John McCalla729c622012-02-17 03:33:10 +00001582
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001583 if (!HasAVXType)
1584 return true;
1585 }
John McCallcbc038a2011-09-21 08:08:30 +00001586
John McCalla729c622012-02-17 03:33:10 +00001587 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001588 }
1589
Craig Topper4f12f102014-03-12 06:41:41 +00001590 llvm::Constant *
1591 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001592 unsigned Sig = (0xeb << 0) | // jmp rel8
1593 (0x0a << 8) | // .+0x0c
1594 ('F' << 16) |
1595 ('T' << 24);
1596 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1597 }
1598
Alexander Musman09184fe2014-09-30 05:29:28 +00001599 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1600 return HasAVX ? 32 : 16;
1601 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001602};
1603
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001604class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1605public:
1606 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1607 : X86_64TargetCodeGenInfo(CGT, HasAVX) {}
1608
1609 void getDependentLibraryOption(llvm::StringRef Lib,
1610 llvm::SmallString<24> &Opt) const {
1611 Opt = "\01";
1612 Opt += Lib;
1613 }
1614};
1615
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001616static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001617 // If the argument does not end in .lib, automatically add the suffix.
1618 // If the argument contains a space, enclose it in quotes.
1619 // This matches the behavior of MSVC.
1620 bool Quote = (Lib.find(" ") != StringRef::npos);
1621 std::string ArgStr = Quote ? "\"" : "";
1622 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001623 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001624 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001625 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001626 return ArgStr;
1627}
1628
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001629class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1630public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001631 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1632 bool d, bool p, bool w, unsigned RegParms)
1633 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001634
Hans Wennborg77dc2362015-01-20 19:45:50 +00001635 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1636 CodeGen::CodeGenModule &CGM) const override;
1637
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001638 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001639 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001640 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001641 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001642 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001643
1644 void getDetectMismatchOption(llvm::StringRef Name,
1645 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001646 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001647 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001648 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001649};
1650
Hans Wennborg77dc2362015-01-20 19:45:50 +00001651static void addStackProbeSizeTargetAttribute(const Decl *D,
1652 llvm::GlobalValue *GV,
1653 CodeGen::CodeGenModule &CGM) {
1654 if (isa<FunctionDecl>(D)) {
1655 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1656 llvm::Function *Fn = cast<llvm::Function>(GV);
1657
1658 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1659 }
1660 }
1661}
1662
1663void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1664 llvm::GlobalValue *GV,
1665 CodeGen::CodeGenModule &CGM) const {
1666 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1667
1668 addStackProbeSizeTargetAttribute(D, GV, CGM);
1669}
1670
Chris Lattner04dc9572010-08-31 16:44:54 +00001671class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001672 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001673public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001674 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1675 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001676
Hans Wennborg77dc2362015-01-20 19:45:50 +00001677 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1678 CodeGen::CodeGenModule &CGM) const override;
1679
Craig Topper4f12f102014-03-12 06:41:41 +00001680 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001681 return 7;
1682 }
1683
1684 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001685 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001686 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001687
Chris Lattner04dc9572010-08-31 16:44:54 +00001688 // 0-15 are the 16 integer registers.
1689 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001690 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001691 return false;
1692 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001693
1694 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001695 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001696 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001697 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001698 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001699
1700 void getDetectMismatchOption(llvm::StringRef Name,
1701 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001702 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001703 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001704 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001705
1706 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1707 return HasAVX ? 32 : 16;
1708 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001709};
1710
Hans Wennborg77dc2362015-01-20 19:45:50 +00001711void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1712 llvm::GlobalValue *GV,
1713 CodeGen::CodeGenModule &CGM) const {
1714 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1715
1716 addStackProbeSizeTargetAttribute(D, GV, CGM);
1717}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001718}
1719
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001720void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1721 Class &Hi) const {
1722 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1723 //
1724 // (a) If one of the classes is Memory, the whole argument is passed in
1725 // memory.
1726 //
1727 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1728 // memory.
1729 //
1730 // (c) If the size of the aggregate exceeds two eightbytes and the first
1731 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1732 // argument is passed in memory. NOTE: This is necessary to keep the
1733 // ABI working for processors that don't support the __m256 type.
1734 //
1735 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1736 //
1737 // Some of these are enforced by the merging logic. Others can arise
1738 // only with unions; for example:
1739 // union { _Complex double; unsigned; }
1740 //
1741 // Note that clauses (b) and (c) were added in 0.98.
1742 //
1743 if (Hi == Memory)
1744 Lo = Memory;
1745 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1746 Lo = Memory;
1747 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1748 Lo = Memory;
1749 if (Hi == SSEUp && Lo != SSE)
1750 Hi = SSE;
1751}
1752
Chris Lattnerd776fb12010-06-28 21:43:59 +00001753X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001754 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1755 // classified recursively so that always two fields are
1756 // considered. The resulting class is calculated according to
1757 // the classes of the fields in the eightbyte:
1758 //
1759 // (a) If both classes are equal, this is the resulting class.
1760 //
1761 // (b) If one of the classes is NO_CLASS, the resulting class is
1762 // the other class.
1763 //
1764 // (c) If one of the classes is MEMORY, the result is the MEMORY
1765 // class.
1766 //
1767 // (d) If one of the classes is INTEGER, the result is the
1768 // INTEGER.
1769 //
1770 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1771 // MEMORY is used as class.
1772 //
1773 // (f) Otherwise class SSE is used.
1774
1775 // Accum should never be memory (we should have returned) or
1776 // ComplexX87 (because this cannot be passed in a structure).
1777 assert((Accum != Memory && Accum != ComplexX87) &&
1778 "Invalid accumulated classification during merge.");
1779 if (Accum == Field || Field == NoClass)
1780 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001781 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001782 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001783 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001784 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001785 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001786 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001787 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1788 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001789 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001790 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001791}
1792
Chris Lattner5c740f12010-06-30 19:14:05 +00001793void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001794 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001795 // FIXME: This code can be simplified by introducing a simple value class for
1796 // Class pairs with appropriate constructor methods for the various
1797 // situations.
1798
1799 // FIXME: Some of the split computations are wrong; unaligned vectors
1800 // shouldn't be passed in registers for example, so there is no chance they
1801 // can straddle an eightbyte. Verify & simplify.
1802
1803 Lo = Hi = NoClass;
1804
1805 Class &Current = OffsetBase < 64 ? Lo : Hi;
1806 Current = Memory;
1807
John McCall9dd450b2009-09-21 23:43:11 +00001808 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001809 BuiltinType::Kind k = BT->getKind();
1810
1811 if (k == BuiltinType::Void) {
1812 Current = NoClass;
1813 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1814 Lo = Integer;
1815 Hi = Integer;
1816 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1817 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001818 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1819 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001820 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001821 Current = SSE;
1822 } else if (k == BuiltinType::LongDouble) {
1823 Lo = X87;
1824 Hi = X87Up;
1825 }
1826 // FIXME: _Decimal32 and _Decimal64 are SSE.
1827 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001828 return;
1829 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001830
Chris Lattnerd776fb12010-06-28 21:43:59 +00001831 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001832 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001833 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001834 return;
1835 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001836
Chris Lattnerd776fb12010-06-28 21:43:59 +00001837 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001838 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001839 return;
1840 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001841
Chris Lattnerd776fb12010-06-28 21:43:59 +00001842 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001843 if (Ty->isMemberFunctionPointerType()) {
1844 if (Has64BitPointers) {
1845 // If Has64BitPointers, this is an {i64, i64}, so classify both
1846 // Lo and Hi now.
1847 Lo = Hi = Integer;
1848 } else {
1849 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1850 // straddles an eightbyte boundary, Hi should be classified as well.
1851 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1852 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1853 if (EB_FuncPtr != EB_ThisAdj) {
1854 Lo = Hi = Integer;
1855 } else {
1856 Current = Integer;
1857 }
1858 }
1859 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001860 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001861 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001862 return;
1863 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001864
Chris Lattnerd776fb12010-06-28 21:43:59 +00001865 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001866 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001867 if (Size == 32) {
1868 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1869 // float> as integer.
1870 Current = Integer;
1871
1872 // If this type crosses an eightbyte boundary, it should be
1873 // split.
1874 uint64_t EB_Real = (OffsetBase) / 64;
1875 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1876 if (EB_Real != EB_Imag)
1877 Hi = Lo;
1878 } else if (Size == 64) {
1879 // gcc passes <1 x double> in memory. :(
1880 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1881 return;
1882
1883 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001884 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001885 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1886 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1887 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001888 Current = Integer;
1889 else
1890 Current = SSE;
1891
1892 // If this type crosses an eightbyte boundary, it should be
1893 // split.
1894 if (OffsetBase && OffsetBase != 64)
1895 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001896 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001897 // Arguments of 256-bits are split into four eightbyte chunks. The
1898 // least significant one belongs to class SSE and all the others to class
1899 // SSEUP. The original Lo and Hi design considers that types can't be
1900 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1901 // This design isn't correct for 256-bits, but since there're no cases
1902 // where the upper parts would need to be inspected, avoid adding
1903 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001904 //
1905 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1906 // registers if they are "named", i.e. not part of the "..." of a
1907 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001908 Lo = SSE;
1909 Hi = SSEUp;
1910 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001911 return;
1912 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001913
Chris Lattnerd776fb12010-06-28 21:43:59 +00001914 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001915 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001916
Chris Lattner2b037972010-07-29 02:01:43 +00001917 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001918 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001919 if (Size <= 64)
1920 Current = Integer;
1921 else if (Size <= 128)
1922 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001923 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001924 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001925 else if (ET == getContext().DoubleTy ||
1926 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001927 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001928 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001929 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001930 Current = ComplexX87;
1931
1932 // If this complex type crosses an eightbyte boundary then it
1933 // should be split.
1934 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001935 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001936 if (Hi == NoClass && EB_Real != EB_Imag)
1937 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001938
Chris Lattnerd776fb12010-06-28 21:43:59 +00001939 return;
1940 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001941
Chris Lattner2b037972010-07-29 02:01:43 +00001942 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001943 // Arrays are treated like structures.
1944
Chris Lattner2b037972010-07-29 02:01:43 +00001945 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001946
1947 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001948 // than four eightbytes, ..., it has class MEMORY.
1949 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001950 return;
1951
1952 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1953 // fields, it has class MEMORY.
1954 //
1955 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001956 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001957 return;
1958
1959 // Otherwise implement simplified merge. We could be smarter about
1960 // this, but it isn't worth it and would be harder to verify.
1961 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001962 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001963 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001964
1965 // The only case a 256-bit wide vector could be used is when the array
1966 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1967 // to work for sizes wider than 128, early check and fallback to memory.
1968 if (Size > 128 && EltSize != 256)
1969 return;
1970
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001971 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1972 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001973 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001974 Lo = merge(Lo, FieldLo);
1975 Hi = merge(Hi, FieldHi);
1976 if (Lo == Memory || Hi == Memory)
1977 break;
1978 }
1979
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001980 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001981 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001982 return;
1983 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001984
Chris Lattnerd776fb12010-06-28 21:43:59 +00001985 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001986 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001987
1988 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001989 // than four eightbytes, ..., it has class MEMORY.
1990 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001991 return;
1992
Anders Carlsson20759ad2009-09-16 15:53:40 +00001993 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1994 // copy constructor or a non-trivial destructor, it is passed by invisible
1995 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001996 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001997 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001998
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001999 const RecordDecl *RD = RT->getDecl();
2000
2001 // Assume variable sized types are passed in memory.
2002 if (RD->hasFlexibleArrayMember())
2003 return;
2004
Chris Lattner2b037972010-07-29 02:01:43 +00002005 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002006
2007 // Reset Lo class, this will be recomputed.
2008 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002009
2010 // If this is a C++ record, classify the bases first.
2011 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002012 for (const auto &I : CXXRD->bases()) {
2013 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002014 "Unexpected base class!");
2015 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002016 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002017
2018 // Classify this field.
2019 //
2020 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2021 // single eightbyte, each is classified separately. Each eightbyte gets
2022 // initialized to class NO_CLASS.
2023 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002024 uint64_t Offset =
2025 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002026 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002027 Lo = merge(Lo, FieldLo);
2028 Hi = merge(Hi, FieldHi);
2029 if (Lo == Memory || Hi == Memory)
2030 break;
2031 }
2032 }
2033
2034 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002035 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002036 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002037 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002038 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2039 bool BitField = i->isBitField();
2040
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002041 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2042 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002043 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002044 // The only case a 256-bit wide vector could be used is when the struct
2045 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2046 // to work for sizes wider than 128, early check and fallback to memory.
2047 //
2048 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2049 Lo = Memory;
2050 return;
2051 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002052 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002053 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002054 Lo = Memory;
2055 return;
2056 }
2057
2058 // Classify this field.
2059 //
2060 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2061 // exceeds a single eightbyte, each is classified
2062 // separately. Each eightbyte gets initialized to class
2063 // NO_CLASS.
2064 Class FieldLo, FieldHi;
2065
2066 // Bit-fields require special handling, they do not force the
2067 // structure to be passed in memory even if unaligned, and
2068 // therefore they can straddle an eightbyte.
2069 if (BitField) {
2070 // Ignore padding bit-fields.
2071 if (i->isUnnamedBitfield())
2072 continue;
2073
2074 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002075 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076
2077 uint64_t EB_Lo = Offset / 64;
2078 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002079
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002080 if (EB_Lo) {
2081 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2082 FieldLo = NoClass;
2083 FieldHi = Integer;
2084 } else {
2085 FieldLo = Integer;
2086 FieldHi = EB_Hi ? Integer : NoClass;
2087 }
2088 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002089 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002090 Lo = merge(Lo, FieldLo);
2091 Hi = merge(Hi, FieldHi);
2092 if (Lo == Memory || Hi == Memory)
2093 break;
2094 }
2095
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002096 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002097 }
2098}
2099
Chris Lattner22a931e2010-06-29 06:01:59 +00002100ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002101 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2102 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002103 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002104 // Treat an enum type as its underlying type.
2105 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2106 Ty = EnumTy->getDecl()->getIntegerType();
2107
2108 return (Ty->isPromotableIntegerType() ?
2109 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2110 }
2111
2112 return ABIArgInfo::getIndirect(0);
2113}
2114
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002115bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2116 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2117 uint64_t Size = getContext().getTypeSize(VecTy);
2118 unsigned LargestVector = HasAVX ? 256 : 128;
2119 if (Size <= 64 || Size > LargestVector)
2120 return true;
2121 }
2122
2123 return false;
2124}
2125
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002126ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2127 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002128 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2129 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002130 //
2131 // This assumption is optimistic, as there could be free registers available
2132 // when we need to pass this argument in memory, and LLVM could try to pass
2133 // the argument in the free register. This does not seem to happen currently,
2134 // but this code would be much safer if we could mark the argument with
2135 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002136 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002137 // Treat an enum type as its underlying type.
2138 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2139 Ty = EnumTy->getDecl()->getIntegerType();
2140
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002141 return (Ty->isPromotableIntegerType() ?
2142 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002143 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002144
Mark Lacey3825e832013-10-06 01:33:34 +00002145 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002146 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002147
Chris Lattner44c2b902011-05-22 23:21:23 +00002148 // Compute the byval alignment. We specify the alignment of the byval in all
2149 // cases so that the mid-level optimizer knows the alignment of the byval.
2150 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002151
2152 // Attempt to avoid passing indirect results using byval when possible. This
2153 // is important for good codegen.
2154 //
2155 // We do this by coercing the value into a scalar type which the backend can
2156 // handle naturally (i.e., without using byval).
2157 //
2158 // For simplicity, we currently only do this when we have exhausted all of the
2159 // free integer registers. Doing this when there are free integer registers
2160 // would require more care, as we would have to ensure that the coerced value
2161 // did not claim the unused register. That would require either reording the
2162 // arguments to the function (so that any subsequent inreg values came first),
2163 // or only doing this optimization when there were no following arguments that
2164 // might be inreg.
2165 //
2166 // We currently expect it to be rare (particularly in well written code) for
2167 // arguments to be passed on the stack when there are still free integer
2168 // registers available (this would typically imply large structs being passed
2169 // by value), so this seems like a fair tradeoff for now.
2170 //
2171 // We can revisit this if the backend grows support for 'onstack' parameter
2172 // attributes. See PR12193.
2173 if (freeIntRegs == 0) {
2174 uint64_t Size = getContext().getTypeSize(Ty);
2175
2176 // If this type fits in an eightbyte, coerce it into the matching integral
2177 // type, which will end up on the stack (with alignment 8).
2178 if (Align == 8 && Size <= 64)
2179 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2180 Size));
2181 }
2182
Chris Lattner44c2b902011-05-22 23:21:23 +00002183 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002184}
2185
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002186/// GetByteVectorType - The ABI specifies that a value should be passed in an
2187/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002188/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002189llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002190 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002191
Chris Lattner9fa15c32010-07-29 05:02:29 +00002192 // Wrapper structs that just contain vectors are passed just like vectors,
2193 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002194 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002195 while (STy && STy->getNumElements() == 1) {
2196 IRType = STy->getElementType(0);
2197 STy = dyn_cast<llvm::StructType>(IRType);
2198 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002199
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002200 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002201 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2202 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002203 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002204 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002205 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2206 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2207 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2208 EltTy->isIntegerTy(128)))
2209 return VT;
2210 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002211
Chris Lattner4200fe42010-07-29 04:56:46 +00002212 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2213}
2214
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002215/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2216/// is known to either be off the end of the specified type or being in
2217/// alignment padding. The user type specified is known to be at most 128 bits
2218/// in size, and have passed through X86_64ABIInfo::classify with a successful
2219/// classification that put one of the two halves in the INTEGER class.
2220///
2221/// It is conservatively correct to return false.
2222static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2223 unsigned EndBit, ASTContext &Context) {
2224 // If the bytes being queried are off the end of the type, there is no user
2225 // data hiding here. This handles analysis of builtins, vectors and other
2226 // types that don't contain interesting padding.
2227 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2228 if (TySize <= StartBit)
2229 return true;
2230
Chris Lattner98076a22010-07-29 07:43:55 +00002231 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2232 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2233 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2234
2235 // Check each element to see if the element overlaps with the queried range.
2236 for (unsigned i = 0; i != NumElts; ++i) {
2237 // If the element is after the span we care about, then we're done..
2238 unsigned EltOffset = i*EltSize;
2239 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002240
Chris Lattner98076a22010-07-29 07:43:55 +00002241 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2242 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2243 EndBit-EltOffset, Context))
2244 return false;
2245 }
2246 // If it overlaps no elements, then it is safe to process as padding.
2247 return true;
2248 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002249
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002250 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2251 const RecordDecl *RD = RT->getDecl();
2252 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002253
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002254 // If this is a C++ record, check the bases first.
2255 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002256 for (const auto &I : CXXRD->bases()) {
2257 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002258 "Unexpected base class!");
2259 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002260 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002261
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002262 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002263 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002264 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002265
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002266 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002267 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002268 EndBit-BaseOffset, Context))
2269 return false;
2270 }
2271 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002272
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002273 // Verify that no field has data that overlaps the region of interest. Yes
2274 // this could be sped up a lot by being smarter about queried fields,
2275 // however we're only looking at structs up to 16 bytes, so we don't care
2276 // much.
2277 unsigned idx = 0;
2278 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2279 i != e; ++i, ++idx) {
2280 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002281
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002282 // If we found a field after the region we care about, then we're done.
2283 if (FieldOffset >= EndBit) break;
2284
2285 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2286 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2287 Context))
2288 return false;
2289 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002290
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002291 // If nothing in this record overlapped the area of interest, then we're
2292 // clean.
2293 return true;
2294 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002295
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002296 return false;
2297}
2298
Chris Lattnere556a712010-07-29 18:39:32 +00002299/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2300/// float member at the specified offset. For example, {int,{float}} has a
2301/// float at offset 4. It is conservatively correct for this routine to return
2302/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002303static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002304 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002305 // Base case if we find a float.
2306 if (IROffset == 0 && IRType->isFloatTy())
2307 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002308
Chris Lattnere556a712010-07-29 18:39:32 +00002309 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002310 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002311 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2312 unsigned Elt = SL->getElementContainingOffset(IROffset);
2313 IROffset -= SL->getElementOffset(Elt);
2314 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2315 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002316
Chris Lattnere556a712010-07-29 18:39:32 +00002317 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002318 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2319 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002320 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2321 IROffset -= IROffset/EltSize*EltSize;
2322 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2323 }
2324
2325 return false;
2326}
2327
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002328
2329/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2330/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002331llvm::Type *X86_64ABIInfo::
2332GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002333 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002334 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002335 // pass as float if the last 4 bytes is just padding. This happens for
2336 // structs that contain 3 floats.
2337 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2338 SourceOffset*8+64, getContext()))
2339 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002340
Chris Lattnere556a712010-07-29 18:39:32 +00002341 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2342 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2343 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002344 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2345 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002346 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002347
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002348 return llvm::Type::getDoubleTy(getVMContext());
2349}
2350
2351
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002352/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2353/// an 8-byte GPR. This means that we either have a scalar or we are talking
2354/// about the high or low part of an up-to-16-byte struct. This routine picks
2355/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002356/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2357/// etc).
2358///
2359/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2360/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2361/// the 8-byte value references. PrefType may be null.
2362///
Alp Toker9907f082014-07-09 14:06:35 +00002363/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002364/// an offset into this that we're processing (which is always either 0 or 8).
2365///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002366llvm::Type *X86_64ABIInfo::
2367GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002368 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002369 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2370 // returning an 8-byte unit starting with it. See if we can safely use it.
2371 if (IROffset == 0) {
2372 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002373 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2374 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002375 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002376
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002377 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2378 // goodness in the source type is just tail padding. This is allowed to
2379 // kick in for struct {double,int} on the int, but not on
2380 // struct{double,int,int} because we wouldn't return the second int. We
2381 // have to do this analysis on the source type because we can't depend on
2382 // unions being lowered a specific way etc.
2383 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002384 IRType->isIntegerTy(32) ||
2385 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2386 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2387 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002388
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002389 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2390 SourceOffset*8+64, getContext()))
2391 return IRType;
2392 }
2393 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002394
Chris Lattner2192fe52011-07-18 04:24:23 +00002395 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002396 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002397 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002398 if (IROffset < SL->getSizeInBytes()) {
2399 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2400 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002401
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002402 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2403 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002404 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002405 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002406
Chris Lattner2192fe52011-07-18 04:24:23 +00002407 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002408 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002409 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002410 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002411 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2412 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002413 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002414
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002415 // Okay, we don't have any better idea of what to pass, so we pass this in an
2416 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002417 unsigned TySizeInBytes =
2418 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002419
Chris Lattner3f763422010-07-29 17:34:39 +00002420 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002421
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002422 // It is always safe to classify this as an integer type up to i64 that
2423 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002424 return llvm::IntegerType::get(getVMContext(),
2425 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002426}
2427
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002428
2429/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2430/// be used as elements of a two register pair to pass or return, return a
2431/// first class aggregate to represent them. For example, if the low part of
2432/// a by-value argument should be passed as i32* and the high part as float,
2433/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002434static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002435GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002436 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002437 // In order to correctly satisfy the ABI, we need to the high part to start
2438 // at offset 8. If the high and low parts we inferred are both 4-byte types
2439 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2440 // the second element at offset 8. Check for this:
2441 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2442 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002443 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002444 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002445
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002446 // To handle this, we have to increase the size of the low part so that the
2447 // second element will start at an 8 byte offset. We can't increase the size
2448 // of the second element because it might make us access off the end of the
2449 // struct.
2450 if (HiStart != 8) {
2451 // There are only two sorts of types the ABI generation code can produce for
2452 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2453 // Promote these to a larger type.
2454 if (Lo->isFloatTy())
2455 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2456 else {
2457 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2458 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2459 }
2460 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002461
Reid Kleckneree7cf842014-12-01 22:02:27 +00002462 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002463
2464
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002465 // Verify that the second element is at an 8-byte offset.
2466 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2467 "Invalid x86-64 argument pair!");
2468 return Result;
2469}
2470
Chris Lattner31faff52010-07-28 23:06:14 +00002471ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002472classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002473 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2474 // classification algorithm.
2475 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002476 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002477
2478 // Check some invariants.
2479 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002480 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2481
Craig Topper8a13c412014-05-21 05:09:00 +00002482 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002483 switch (Lo) {
2484 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002485 if (Hi == NoClass)
2486 return ABIArgInfo::getIgnore();
2487 // If the low part is just padding, it takes no register, leave ResType
2488 // null.
2489 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2490 "Unknown missing lo part");
2491 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002492
2493 case SSEUp:
2494 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002495 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002496
2497 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2498 // hidden argument.
2499 case Memory:
2500 return getIndirectReturnResult(RetTy);
2501
2502 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2503 // available register of the sequence %rax, %rdx is used.
2504 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002505 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002506
Chris Lattner1f3a0632010-07-29 21:42:50 +00002507 // If we have a sign or zero extended integer, make sure to return Extend
2508 // so that the parameter gets the right LLVM IR attributes.
2509 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2510 // Treat an enum type as its underlying type.
2511 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2512 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002513
Chris Lattner1f3a0632010-07-29 21:42:50 +00002514 if (RetTy->isIntegralOrEnumerationType() &&
2515 RetTy->isPromotableIntegerType())
2516 return ABIArgInfo::getExtend();
2517 }
Chris Lattner31faff52010-07-28 23:06:14 +00002518 break;
2519
2520 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2521 // available SSE register of the sequence %xmm0, %xmm1 is used.
2522 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002523 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002524 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002525
2526 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2527 // returned on the X87 stack in %st0 as 80-bit x87 number.
2528 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002529 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002530 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002531
2532 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2533 // part of the value is returned in %st0 and the imaginary part in
2534 // %st1.
2535 case ComplexX87:
2536 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002537 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002538 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002539 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002540 break;
2541 }
2542
Craig Topper8a13c412014-05-21 05:09:00 +00002543 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002544 switch (Hi) {
2545 // Memory was handled previously and X87 should
2546 // never occur as a hi class.
2547 case Memory:
2548 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002549 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002550
2551 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002552 case NoClass:
2553 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002554
Chris Lattner52b3c132010-09-01 00:20:33 +00002555 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002556 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002557 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2558 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002559 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002560 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002561 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002562 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2563 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002564 break;
2565
2566 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002567 // is passed in the next available eightbyte chunk if the last used
2568 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002569 //
Chris Lattner57540c52011-04-15 05:22:18 +00002570 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002571 case SSEUp:
2572 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002573 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002574 break;
2575
2576 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2577 // returned together with the previous X87 value in %st0.
2578 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002579 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002580 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002581 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002582 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002583 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002584 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002585 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2586 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002587 }
Chris Lattner31faff52010-07-28 23:06:14 +00002588 break;
2589 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002590
Chris Lattner52b3c132010-09-01 00:20:33 +00002591 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002592 // known to pass in the high eightbyte of the result. We do this by forming a
2593 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002594 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002595 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002596
Chris Lattner1f3a0632010-07-29 21:42:50 +00002597 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002598}
2599
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002600ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002601 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2602 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002603 const
2604{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002605 Ty = useFirstFieldIfTransparentUnion(Ty);
2606
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002607 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002608 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002609
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002610 // Check some invariants.
2611 // FIXME: Enforce these by construction.
2612 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2614
2615 neededInt = 0;
2616 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002617 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 switch (Lo) {
2619 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002620 if (Hi == NoClass)
2621 return ABIArgInfo::getIgnore();
2622 // If the low part is just padding, it takes no register, leave ResType
2623 // null.
2624 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2625 "Unknown missing lo part");
2626 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002627
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002628 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2629 // on the stack.
2630 case Memory:
2631
2632 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2633 // COMPLEX_X87, it is passed in memory.
2634 case X87:
2635 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002636 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002637 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002638 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639
2640 case SSEUp:
2641 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002642 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002643
2644 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2645 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2646 // and %r9 is used.
2647 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002648 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002649
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002650 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002651 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002652
2653 // If we have a sign or zero extended integer, make sure to return Extend
2654 // so that the parameter gets the right LLVM IR attributes.
2655 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2656 // Treat an enum type as its underlying type.
2657 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2658 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002659
Chris Lattner1f3a0632010-07-29 21:42:50 +00002660 if (Ty->isIntegralOrEnumerationType() &&
2661 Ty->isPromotableIntegerType())
2662 return ABIArgInfo::getExtend();
2663 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002664
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002665 break;
2666
2667 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2668 // available SSE register is used, the registers are taken in the
2669 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002670 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002671 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002672 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002673 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674 break;
2675 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002676 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002677
Craig Topper8a13c412014-05-21 05:09:00 +00002678 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679 switch (Hi) {
2680 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002681 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682 // which is passed in memory.
2683 case Memory:
2684 case X87:
2685 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002686 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002687
2688 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002689
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002690 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002691 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002692 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002693 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002694
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002695 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2696 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002697 break;
2698
2699 // X87Up generally doesn't occur here (long double is passed in
2700 // memory), except in situations involving unions.
2701 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002702 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002703 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002704
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002705 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2706 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002707
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708 ++neededSSE;
2709 break;
2710
2711 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2712 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002713 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002715 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002716 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002717 break;
2718 }
2719
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002720 // If a high part was specified, merge it together with the low part. It is
2721 // known to pass in the high eightbyte of the result. We do this by forming a
2722 // first class struct aggregate with the high and low part: {low, high}
2723 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002724 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002725
Chris Lattner1f3a0632010-07-29 21:42:50 +00002726 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727}
2728
Chris Lattner22326a12010-07-29 02:31:05 +00002729void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002730
Reid Kleckner40ca9132014-05-13 22:05:45 +00002731 if (!getCXXABI().classifyReturnType(FI))
2732 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002733
2734 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002735 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002736
2737 // If the return value is indirect, then the hidden argument is consuming one
2738 // integer register.
2739 if (FI.getReturnInfo().isIndirect())
2740 --freeIntRegs;
2741
Peter Collingbournef7706832014-12-12 23:41:25 +00002742 // The chain argument effectively gives us another free register.
2743 if (FI.isChainCall())
2744 ++freeIntRegs;
2745
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002746 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2748 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002749 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002751 it != ie; ++it, ++ArgNo) {
2752 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002753
Bill Wendling9987c0e2010-10-18 23:51:38 +00002754 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002755 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002756 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002757
2758 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2759 // eightbyte of an argument, the whole argument is passed on the
2760 // stack. If registers have already been assigned for some
2761 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002762 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002763 freeIntRegs -= neededInt;
2764 freeSSERegs -= neededSSE;
2765 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002766 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002767 }
2768 }
2769}
2770
2771static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2772 QualType Ty,
2773 CodeGenFunction &CGF) {
2774 llvm::Value *overflow_arg_area_p =
2775 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2776 llvm::Value *overflow_arg_area =
2777 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2778
2779 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2780 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002781 // It isn't stated explicitly in the standard, but in practice we use
2782 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002783 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2784 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002785 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002786 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002787 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002788 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2789 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002790 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002791 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002792 overflow_arg_area =
2793 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2794 overflow_arg_area->getType(),
2795 "overflow_arg_area.align");
2796 }
2797
2798 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002799 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002800 llvm::Value *Res =
2801 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002802 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803
2804 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2805 // l->overflow_arg_area + sizeof(type).
2806 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2807 // an 8 byte boundary.
2808
2809 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002810 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002811 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002812 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2813 "overflow_arg_area.next");
2814 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2815
2816 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2817 return Res;
2818}
2819
2820llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2821 CodeGenFunction &CGF) const {
2822 // Assume that va_list type is correct; should be pointer to LLVM type:
2823 // struct {
2824 // i32 gp_offset;
2825 // i32 fp_offset;
2826 // i8* overflow_arg_area;
2827 // i8* reg_save_area;
2828 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002829 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002830
Chris Lattner9723d6c2010-03-11 18:19:55 +00002831 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002832 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2833 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002834
2835 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2836 // in the registers. If not go to step 7.
2837 if (!neededInt && !neededSSE)
2838 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2839
2840 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2841 // general purpose registers needed to pass type and num_fp to hold
2842 // the number of floating point registers needed.
2843
2844 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2845 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2846 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2847 //
2848 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2849 // register save space).
2850
Craig Topper8a13c412014-05-21 05:09:00 +00002851 llvm::Value *InRegs = nullptr;
2852 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2853 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002854 if (neededInt) {
2855 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2856 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002857 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2858 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002859 }
2860
2861 if (neededSSE) {
2862 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2863 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2864 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002865 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2866 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002867 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2868 }
2869
2870 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2871 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2872 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2873 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2874
2875 // Emit code to load the value if it was passed in registers.
2876
2877 CGF.EmitBlock(InRegBlock);
2878
2879 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2880 // an offset of l->gp_offset and/or l->fp_offset. This may require
2881 // copying to a temporary location in case the parameter is passed
2882 // in different register classes or requires an alignment greater
2883 // than 8 for general purpose registers and 16 for XMM registers.
2884 //
2885 // FIXME: This really results in shameful code when we end up needing to
2886 // collect arguments from different places; often what should result in a
2887 // simple assembling of a structure from scattered addresses has many more
2888 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002889 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002890 llvm::Value *RegAddr =
2891 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2892 "reg_save_area");
2893 if (neededInt && neededSSE) {
2894 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002895 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002896 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002897 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2898 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002899 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002900 llvm::Type *TyLo = ST->getElementType(0);
2901 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002902 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002903 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002904 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2905 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002906 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2907 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002908 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2909 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002910 llvm::Value *V =
2911 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2912 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2913 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2914 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2915
Owen Anderson170229f2009-07-14 23:10:40 +00002916 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002917 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002918 } else if (neededInt) {
2919 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2920 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002921 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002922
2923 // Copy to a temporary if necessary to ensure the appropriate alignment.
2924 std::pair<CharUnits, CharUnits> SizeAlign =
2925 CGF.getContext().getTypeInfoInChars(Ty);
2926 uint64_t TySize = SizeAlign.first.getQuantity();
2927 unsigned TyAlign = SizeAlign.second.getQuantity();
2928 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002929 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2930 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2931 RegAddr = Tmp;
2932 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002933 } else if (neededSSE == 1) {
2934 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2935 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2936 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002937 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002938 assert(neededSSE == 2 && "Invalid number of needed registers!");
2939 // SSE registers are spaced 16 bytes apart in the register save
2940 // area, we need to collect the two eightbytes together.
2941 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002942 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002943 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002944 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002945 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002946 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002947 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2948 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002949 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2950 DblPtrTy));
2951 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2952 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2953 DblPtrTy));
2954 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2955 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2956 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002957 }
2958
2959 // AMD64-ABI 3.5.7p5: Step 5. Set:
2960 // l->gp_offset = l->gp_offset + num_gp * 8
2961 // l->fp_offset = l->fp_offset + num_fp * 16.
2962 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002963 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002964 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2965 gp_offset_p);
2966 }
2967 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002968 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002969 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2970 fp_offset_p);
2971 }
2972 CGF.EmitBranch(ContBlock);
2973
2974 // Emit code to load the value if it was passed in memory.
2975
2976 CGF.EmitBlock(InMemBlock);
2977 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2978
2979 // Return the appropriate result.
2980
2981 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002982 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002983 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002984 ResAddr->addIncoming(RegAddr, InRegBlock);
2985 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002986 return ResAddr;
2987}
2988
Reid Kleckner80944df2014-10-31 22:00:51 +00002989ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2990 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002991
2992 if (Ty->isVoidType())
2993 return ABIArgInfo::getIgnore();
2994
2995 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2996 Ty = EnumTy->getDecl()->getIntegerType();
2997
Reid Kleckner80944df2014-10-31 22:00:51 +00002998 TypeInfo Info = getContext().getTypeInfo(Ty);
2999 uint64_t Width = Info.Width;
3000 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003001
Reid Kleckner9005f412014-05-02 00:51:20 +00003002 const RecordType *RT = Ty->getAs<RecordType>();
3003 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003004 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003005 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003006 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3007 }
3008
3009 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003010 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3011
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003012 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003013 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003014 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003015 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003016 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003017
Reid Kleckner80944df2014-10-31 22:00:51 +00003018 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3019 // other targets.
3020 const Type *Base = nullptr;
3021 uint64_t NumElts = 0;
3022 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3023 if (FreeSSERegs >= NumElts) {
3024 FreeSSERegs -= NumElts;
3025 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3026 return ABIArgInfo::getDirect();
3027 return ABIArgInfo::getExpand();
3028 }
3029 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3030 }
3031
3032
Reid Klecknerec87fec2014-05-02 01:17:12 +00003033 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003034 // If the member pointer is represented by an LLVM int or ptr, pass it
3035 // directly.
3036 llvm::Type *LLTy = CGT.ConvertType(Ty);
3037 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3038 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003039 }
3040
3041 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003042 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3043 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003044 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003045 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003046
Reid Kleckner9005f412014-05-02 00:51:20 +00003047 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003048 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003049 }
3050
Julien Lerouge10dcff82014-08-27 00:36:55 +00003051 // Bool type is always extended to the ABI, other builtin types are not
3052 // extended.
3053 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3054 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003055 return ABIArgInfo::getExtend();
3056
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003057 return ABIArgInfo::getDirect();
3058}
3059
3060void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003061 bool IsVectorCall =
3062 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003063
Reid Kleckner80944df2014-10-31 22:00:51 +00003064 // We can use up to 4 SSE return registers with vectorcall.
3065 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3066 if (!getCXXABI().classifyReturnType(FI))
3067 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3068
3069 // We can use up to 6 SSE register parameters with vectorcall.
3070 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003071 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003072 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003073}
3074
Chris Lattner04dc9572010-08-31 16:44:54 +00003075llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3076 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003077 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003078
Chris Lattner04dc9572010-08-31 16:44:54 +00003079 CGBuilderTy &Builder = CGF.Builder;
3080 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3081 "ap");
3082 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3083 llvm::Type *PTy =
3084 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3085 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3086
3087 uint64_t Offset =
3088 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3089 llvm::Value *NextAddr =
3090 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3091 "ap.next");
3092 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3093
3094 return AddrTyped;
3095}
Chris Lattner0cf24192010-06-28 20:05:43 +00003096
John McCallea8d8bb2010-03-11 00:10:12 +00003097// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003098namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003099/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3100class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003101public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003102 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3103
3104 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3105 CodeGenFunction &CGF) const override;
3106};
3107
3108class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3109public:
3110 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003111
Craig Topper4f12f102014-03-12 06:41:41 +00003112 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003113 // This is recovered from gcc output.
3114 return 1; // r1 is the dedicated stack pointer
3115 }
3116
3117 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003118 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003119
3120 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3121 return 16; // Natural alignment for Altivec vectors.
3122 }
John McCallea8d8bb2010-03-11 00:10:12 +00003123};
3124
3125}
3126
Roman Divacky8a12d842014-11-03 18:32:54 +00003127llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3128 QualType Ty,
3129 CodeGenFunction &CGF) const {
3130 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3131 // TODO: Implement this. For now ignore.
3132 (void)CTy;
3133 return nullptr;
3134 }
3135
3136 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3137 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3138 llvm::Type *CharPtr = CGF.Int8PtrTy;
3139 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3140
3141 CGBuilderTy &Builder = CGF.Builder;
3142 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3143 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3144 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3145 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3146 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3147 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3148 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3149 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3150 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3151 // Align GPR when TY is i64.
3152 if (isI64) {
3153 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3154 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3155 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3156 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3157 }
3158 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3159 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3160 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3161 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3162 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3163
3164 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3165 Builder.getInt8(8), "cond");
3166
3167 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3168 Builder.getInt8(isInt ? 4 : 8));
3169
3170 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3171
3172 if (Ty->isFloatingType())
3173 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3174
3175 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3176 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3177 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3178
3179 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3180
3181 CGF.EmitBlock(UsingRegs);
3182
3183 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3184 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3185 // Increase the GPR/FPR indexes.
3186 if (isInt) {
3187 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3188 Builder.CreateStore(GPR, GPRPtr);
3189 } else {
3190 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3191 Builder.CreateStore(FPR, FPRPtr);
3192 }
3193 CGF.EmitBranch(Cont);
3194
3195 CGF.EmitBlock(UsingOverflow);
3196
3197 // Increase the overflow area.
3198 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3199 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3200 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3201 CGF.EmitBranch(Cont);
3202
3203 CGF.EmitBlock(Cont);
3204
3205 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3206 Result->addIncoming(Result1, UsingRegs);
3207 Result->addIncoming(Result2, UsingOverflow);
3208
3209 if (Ty->isAggregateType()) {
3210 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3211 return Builder.CreateLoad(AGGPtr, false, "aggr");
3212 }
3213
3214 return Result;
3215}
3216
John McCallea8d8bb2010-03-11 00:10:12 +00003217bool
3218PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3219 llvm::Value *Address) const {
3220 // This is calculated from the LLVM and GCC tables and verified
3221 // against gcc output. AFAIK all ABIs use the same encoding.
3222
3223 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003224
Chris Lattnerece04092012-02-07 00:39:47 +00003225 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003226 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3227 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3228 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3229
3230 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003231 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003232
3233 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003234 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003235
3236 // 64-76 are various 4-byte special-purpose registers:
3237 // 64: mq
3238 // 65: lr
3239 // 66: ctr
3240 // 67: ap
3241 // 68-75 cr0-7
3242 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003243 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003244
3245 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003246 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003247
3248 // 109: vrsave
3249 // 110: vscr
3250 // 111: spe_acc
3251 // 112: spefscr
3252 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003253 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003254
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003255 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003256}
3257
Roman Divackyd966e722012-05-09 18:22:46 +00003258// PowerPC-64
3259
3260namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003261/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3262class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003263public:
3264 enum ABIKind {
3265 ELFv1 = 0,
3266 ELFv2
3267 };
3268
3269private:
3270 static const unsigned GPRBits = 64;
3271 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003272
3273public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003274 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3275 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003276
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003277 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003278 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003279
3280 ABIArgInfo classifyReturnType(QualType RetTy) const;
3281 ABIArgInfo classifyArgumentType(QualType Ty) const;
3282
Reid Klecknere9f6a712014-10-31 17:10:41 +00003283 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3284 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3285 uint64_t Members) const override;
3286
Bill Schmidt84d37792012-10-12 19:26:17 +00003287 // TODO: We can add more logic to computeInfo to improve performance.
3288 // Example: For aggregate arguments that fit in a register, we could
3289 // use getDirectInReg (as is done below for structs containing a single
3290 // floating-point value) to avoid pushing them to memory on function
3291 // entry. This would require changing the logic in PPCISelLowering
3292 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003293 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003294 if (!getCXXABI().classifyReturnType(FI))
3295 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003296 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003297 // We rely on the default argument classification for the most part.
3298 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003299 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003300 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003301 if (T) {
3302 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003303 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3304 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003305 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003306 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003307 continue;
3308 }
3309 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003310 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003311 }
3312 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003313
Craig Topper4f12f102014-03-12 06:41:41 +00003314 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3315 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003316};
3317
3318class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3319public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003320 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3321 PPC64_SVR4_ABIInfo::ABIKind Kind)
3322 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003323
Craig Topper4f12f102014-03-12 06:41:41 +00003324 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003325 // This is recovered from gcc output.
3326 return 1; // r1 is the dedicated stack pointer
3327 }
3328
3329 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003330 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003331
3332 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3333 return 16; // Natural alignment for Altivec and VSX vectors.
3334 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003335};
3336
Roman Divackyd966e722012-05-09 18:22:46 +00003337class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3338public:
3339 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3340
Craig Topper4f12f102014-03-12 06:41:41 +00003341 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003342 // This is recovered from gcc output.
3343 return 1; // r1 is the dedicated stack pointer
3344 }
3345
3346 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003347 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003348
3349 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3350 return 16; // Natural alignment for Altivec vectors.
3351 }
Roman Divackyd966e722012-05-09 18:22:46 +00003352};
3353
3354}
3355
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003356// Return true if the ABI requires Ty to be passed sign- or zero-
3357// extended to 64 bits.
3358bool
3359PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3360 // Treat an enum type as its underlying type.
3361 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3362 Ty = EnumTy->getDecl()->getIntegerType();
3363
3364 // Promotable integer types are required to be promoted by the ABI.
3365 if (Ty->isPromotableIntegerType())
3366 return true;
3367
3368 // In addition to the usual promotable integer types, we also need to
3369 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3370 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3371 switch (BT->getKind()) {
3372 case BuiltinType::Int:
3373 case BuiltinType::UInt:
3374 return true;
3375 default:
3376 break;
3377 }
3378
3379 return false;
3380}
3381
Ulrich Weigand581badc2014-07-10 17:20:07 +00003382/// isAlignedParamType - Determine whether a type requires 16-byte
3383/// alignment in the parameter area.
3384bool
3385PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3386 // Complex types are passed just like their elements.
3387 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3388 Ty = CTy->getElementType();
3389
3390 // Only vector types of size 16 bytes need alignment (larger types are
3391 // passed via reference, smaller types are not aligned).
3392 if (Ty->isVectorType())
3393 return getContext().getTypeSize(Ty) == 128;
3394
3395 // For single-element float/vector structs, we consider the whole type
3396 // to have the same alignment requirements as its single element.
3397 const Type *AlignAsType = nullptr;
3398 const Type *EltType = isSingleElementStruct(Ty, getContext());
3399 if (EltType) {
3400 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3401 if ((EltType->isVectorType() &&
3402 getContext().getTypeSize(EltType) == 128) ||
3403 (BT && BT->isFloatingPoint()))
3404 AlignAsType = EltType;
3405 }
3406
Ulrich Weigandb7122372014-07-21 00:48:09 +00003407 // Likewise for ELFv2 homogeneous aggregates.
3408 const Type *Base = nullptr;
3409 uint64_t Members = 0;
3410 if (!AlignAsType && Kind == ELFv2 &&
3411 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3412 AlignAsType = Base;
3413
Ulrich Weigand581badc2014-07-10 17:20:07 +00003414 // With special case aggregates, only vector base types need alignment.
3415 if (AlignAsType)
3416 return AlignAsType->isVectorType();
3417
3418 // Otherwise, we only need alignment for any aggregate type that
3419 // has an alignment requirement of >= 16 bytes.
3420 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3421 return true;
3422
3423 return false;
3424}
3425
Ulrich Weigandb7122372014-07-21 00:48:09 +00003426/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3427/// aggregate. Base is set to the base element type, and Members is set
3428/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003429bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3430 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003431 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3432 uint64_t NElements = AT->getSize().getZExtValue();
3433 if (NElements == 0)
3434 return false;
3435 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3436 return false;
3437 Members *= NElements;
3438 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3439 const RecordDecl *RD = RT->getDecl();
3440 if (RD->hasFlexibleArrayMember())
3441 return false;
3442
3443 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003444
3445 // If this is a C++ record, check the bases first.
3446 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3447 for (const auto &I : CXXRD->bases()) {
3448 // Ignore empty records.
3449 if (isEmptyRecord(getContext(), I.getType(), true))
3450 continue;
3451
3452 uint64_t FldMembers;
3453 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3454 return false;
3455
3456 Members += FldMembers;
3457 }
3458 }
3459
Ulrich Weigandb7122372014-07-21 00:48:09 +00003460 for (const auto *FD : RD->fields()) {
3461 // Ignore (non-zero arrays of) empty records.
3462 QualType FT = FD->getType();
3463 while (const ConstantArrayType *AT =
3464 getContext().getAsConstantArrayType(FT)) {
3465 if (AT->getSize().getZExtValue() == 0)
3466 return false;
3467 FT = AT->getElementType();
3468 }
3469 if (isEmptyRecord(getContext(), FT, true))
3470 continue;
3471
3472 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3473 if (getContext().getLangOpts().CPlusPlus &&
3474 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3475 continue;
3476
3477 uint64_t FldMembers;
3478 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3479 return false;
3480
3481 Members = (RD->isUnion() ?
3482 std::max(Members, FldMembers) : Members + FldMembers);
3483 }
3484
3485 if (!Base)
3486 return false;
3487
3488 // Ensure there is no padding.
3489 if (getContext().getTypeSize(Base) * Members !=
3490 getContext().getTypeSize(Ty))
3491 return false;
3492 } else {
3493 Members = 1;
3494 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3495 Members = 2;
3496 Ty = CT->getElementType();
3497 }
3498
Reid Klecknere9f6a712014-10-31 17:10:41 +00003499 // Most ABIs only support float, double, and some vector type widths.
3500 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003501 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003502
3503 // The base type must be the same for all members. Types that
3504 // agree in both total size and mode (float vs. vector) are
3505 // treated as being equivalent here.
3506 const Type *TyPtr = Ty.getTypePtr();
3507 if (!Base)
3508 Base = TyPtr;
3509
3510 if (Base->isVectorType() != TyPtr->isVectorType() ||
3511 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3512 return false;
3513 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003514 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3515}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003516
Reid Klecknere9f6a712014-10-31 17:10:41 +00003517bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3518 // Homogeneous aggregates for ELFv2 must have base types of float,
3519 // double, long double, or 128-bit vectors.
3520 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3521 if (BT->getKind() == BuiltinType::Float ||
3522 BT->getKind() == BuiltinType::Double ||
3523 BT->getKind() == BuiltinType::LongDouble)
3524 return true;
3525 }
3526 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3527 if (getContext().getTypeSize(VT) == 128)
3528 return true;
3529 }
3530 return false;
3531}
3532
3533bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3534 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003535 // Vector types require one register, floating point types require one
3536 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003537 uint32_t NumRegs =
3538 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003539
3540 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003541 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003542}
3543
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003544ABIArgInfo
3545PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003546 Ty = useFirstFieldIfTransparentUnion(Ty);
3547
Bill Schmidt90b22c92012-11-27 02:46:43 +00003548 if (Ty->isAnyComplexType())
3549 return ABIArgInfo::getDirect();
3550
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003551 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3552 // or via reference (larger than 16 bytes).
3553 if (Ty->isVectorType()) {
3554 uint64_t Size = getContext().getTypeSize(Ty);
3555 if (Size > 128)
3556 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3557 else if (Size < 128) {
3558 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3559 return ABIArgInfo::getDirect(CoerceTy);
3560 }
3561 }
3562
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003563 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003564 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003565 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003566
Ulrich Weigand581badc2014-07-10 17:20:07 +00003567 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3568 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003569
3570 // ELFv2 homogeneous aggregates are passed as array types.
3571 const Type *Base = nullptr;
3572 uint64_t Members = 0;
3573 if (Kind == ELFv2 &&
3574 isHomogeneousAggregate(Ty, Base, Members)) {
3575 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3576 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3577 return ABIArgInfo::getDirect(CoerceTy);
3578 }
3579
Ulrich Weigand601957f2014-07-21 00:56:36 +00003580 // If an aggregate may end up fully in registers, we do not
3581 // use the ByVal method, but pass the aggregate as array.
3582 // This is usually beneficial since we avoid forcing the
3583 // back-end to store the argument to memory.
3584 uint64_t Bits = getContext().getTypeSize(Ty);
3585 if (Bits > 0 && Bits <= 8 * GPRBits) {
3586 llvm::Type *CoerceTy;
3587
3588 // Types up to 8 bytes are passed as integer type (which will be
3589 // properly aligned in the argument save area doubleword).
3590 if (Bits <= GPRBits)
3591 CoerceTy = llvm::IntegerType::get(getVMContext(),
3592 llvm::RoundUpToAlignment(Bits, 8));
3593 // Larger types are passed as arrays, with the base type selected
3594 // according to the required alignment in the save area.
3595 else {
3596 uint64_t RegBits = ABIAlign * 8;
3597 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3598 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3599 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3600 }
3601
3602 return ABIArgInfo::getDirect(CoerceTy);
3603 }
3604
Ulrich Weigandb7122372014-07-21 00:48:09 +00003605 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003606 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3607 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003608 }
3609
3610 return (isPromotableTypeForABI(Ty) ?
3611 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3612}
3613
3614ABIArgInfo
3615PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3616 if (RetTy->isVoidType())
3617 return ABIArgInfo::getIgnore();
3618
Bill Schmidta3d121c2012-12-17 04:20:17 +00003619 if (RetTy->isAnyComplexType())
3620 return ABIArgInfo::getDirect();
3621
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003622 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3623 // or via reference (larger than 16 bytes).
3624 if (RetTy->isVectorType()) {
3625 uint64_t Size = getContext().getTypeSize(RetTy);
3626 if (Size > 128)
3627 return ABIArgInfo::getIndirect(0);
3628 else if (Size < 128) {
3629 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3630 return ABIArgInfo::getDirect(CoerceTy);
3631 }
3632 }
3633
Ulrich Weigandb7122372014-07-21 00:48:09 +00003634 if (isAggregateTypeForABI(RetTy)) {
3635 // ELFv2 homogeneous aggregates are returned as array types.
3636 const Type *Base = nullptr;
3637 uint64_t Members = 0;
3638 if (Kind == ELFv2 &&
3639 isHomogeneousAggregate(RetTy, Base, Members)) {
3640 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3641 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3642 return ABIArgInfo::getDirect(CoerceTy);
3643 }
3644
3645 // ELFv2 small aggregates are returned in up to two registers.
3646 uint64_t Bits = getContext().getTypeSize(RetTy);
3647 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3648 if (Bits == 0)
3649 return ABIArgInfo::getIgnore();
3650
3651 llvm::Type *CoerceTy;
3652 if (Bits > GPRBits) {
3653 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003654 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003655 } else
3656 CoerceTy = llvm::IntegerType::get(getVMContext(),
3657 llvm::RoundUpToAlignment(Bits, 8));
3658 return ABIArgInfo::getDirect(CoerceTy);
3659 }
3660
3661 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003662 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003663 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003664
3665 return (isPromotableTypeForABI(RetTy) ?
3666 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3667}
3668
Bill Schmidt25cb3492012-10-03 19:18:57 +00003669// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3670llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3671 QualType Ty,
3672 CodeGenFunction &CGF) const {
3673 llvm::Type *BP = CGF.Int8PtrTy;
3674 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3675
3676 CGBuilderTy &Builder = CGF.Builder;
3677 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3678 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3679
Ulrich Weigand581badc2014-07-10 17:20:07 +00003680 // Handle types that require 16-byte alignment in the parameter save area.
3681 if (isAlignedParamType(Ty)) {
3682 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3683 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3684 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3685 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3686 }
3687
Bill Schmidt924c4782013-01-14 17:45:36 +00003688 // Update the va_list pointer. The pointer should be bumped by the
3689 // size of the object. We can trust getTypeSize() except for a complex
3690 // type whose base type is smaller than a doubleword. For these, the
3691 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003692 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003693 QualType BaseTy;
3694 unsigned CplxBaseSize = 0;
3695
3696 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3697 BaseTy = CTy->getElementType();
3698 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3699 if (CplxBaseSize < 8)
3700 SizeInBytes = 16;
3701 }
3702
Bill Schmidt25cb3492012-10-03 19:18:57 +00003703 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3704 llvm::Value *NextAddr =
3705 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3706 "ap.next");
3707 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3708
Bill Schmidt924c4782013-01-14 17:45:36 +00003709 // If we have a complex type and the base type is smaller than 8 bytes,
3710 // the ABI calls for the real and imaginary parts to be right-adjusted
3711 // in separate doublewords. However, Clang expects us to produce a
3712 // pointer to a structure with the two parts packed tightly. So generate
3713 // loads of the real and imaginary parts relative to the va_list pointer,
3714 // and store them to a temporary structure.
3715 if (CplxBaseSize && CplxBaseSize < 8) {
3716 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3717 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003718 if (CGF.CGM.getDataLayout().isBigEndian()) {
3719 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3720 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3721 } else {
3722 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3723 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003724 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3725 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3726 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3727 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3728 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3729 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3730 "vacplx");
3731 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3732 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3733 Builder.CreateStore(Real, RealPtr, false);
3734 Builder.CreateStore(Imag, ImagPtr, false);
3735 return Ptr;
3736 }
3737
Bill Schmidt25cb3492012-10-03 19:18:57 +00003738 // If the argument is smaller than 8 bytes, it is right-adjusted in
3739 // its doubleword slot. Adjust the pointer to pick it up from the
3740 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003741 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003742 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3743 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3744 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3745 }
3746
3747 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3748 return Builder.CreateBitCast(Addr, PTy);
3749}
3750
3751static bool
3752PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3753 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003754 // This is calculated from the LLVM and GCC tables and verified
3755 // against gcc output. AFAIK all ABIs use the same encoding.
3756
3757 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3758
3759 llvm::IntegerType *i8 = CGF.Int8Ty;
3760 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3761 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3762 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3763
3764 // 0-31: r0-31, the 8-byte general-purpose registers
3765 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3766
3767 // 32-63: fp0-31, the 8-byte floating-point registers
3768 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3769
3770 // 64-76 are various 4-byte special-purpose registers:
3771 // 64: mq
3772 // 65: lr
3773 // 66: ctr
3774 // 67: ap
3775 // 68-75 cr0-7
3776 // 76: xer
3777 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3778
3779 // 77-108: v0-31, the 16-byte vector registers
3780 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3781
3782 // 109: vrsave
3783 // 110: vscr
3784 // 111: spe_acc
3785 // 112: spefscr
3786 // 113: sfp
3787 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3788
3789 return false;
3790}
John McCallea8d8bb2010-03-11 00:10:12 +00003791
Bill Schmidt25cb3492012-10-03 19:18:57 +00003792bool
3793PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3794 CodeGen::CodeGenFunction &CGF,
3795 llvm::Value *Address) const {
3796
3797 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3798}
3799
3800bool
3801PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3802 llvm::Value *Address) const {
3803
3804 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3805}
3806
Chris Lattner0cf24192010-06-28 20:05:43 +00003807//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003808// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003809//===----------------------------------------------------------------------===//
3810
3811namespace {
3812
Tim Northover573cbee2014-05-24 12:52:07 +00003813class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003814public:
3815 enum ABIKind {
3816 AAPCS = 0,
3817 DarwinPCS
3818 };
3819
3820private:
3821 ABIKind Kind;
3822
3823public:
Tim Northover573cbee2014-05-24 12:52:07 +00003824 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003825
3826private:
3827 ABIKind getABIKind() const { return Kind; }
3828 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3829
3830 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003831 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003832 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3833 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3834 uint64_t Members) const override;
3835
Tim Northovera2ee4332014-03-29 15:09:45 +00003836 bool isIllegalVectorType(QualType Ty) const;
3837
David Blaikie1cbb9712014-11-14 19:09:44 +00003838 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003839 if (!getCXXABI().classifyReturnType(FI))
3840 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003841
Tim Northoverb047bfa2014-11-27 21:02:49 +00003842 for (auto &it : FI.arguments())
3843 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003844 }
3845
3846 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3847 CodeGenFunction &CGF) const;
3848
3849 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3850 CodeGenFunction &CGF) const;
3851
3852 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003853 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003854 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3855 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3856 }
3857};
3858
Tim Northover573cbee2014-05-24 12:52:07 +00003859class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003860public:
Tim Northover573cbee2014-05-24 12:52:07 +00003861 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3862 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003863
3864 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3865 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3866 }
3867
3868 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3869
3870 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3871};
3872}
3873
Tim Northoverb047bfa2014-11-27 21:02:49 +00003874ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003875 Ty = useFirstFieldIfTransparentUnion(Ty);
3876
Tim Northovera2ee4332014-03-29 15:09:45 +00003877 // Handle illegal vector types here.
3878 if (isIllegalVectorType(Ty)) {
3879 uint64_t Size = getContext().getTypeSize(Ty);
3880 if (Size <= 32) {
3881 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003882 return ABIArgInfo::getDirect(ResType);
3883 }
3884 if (Size == 64) {
3885 llvm::Type *ResType =
3886 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003887 return ABIArgInfo::getDirect(ResType);
3888 }
3889 if (Size == 128) {
3890 llvm::Type *ResType =
3891 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003892 return ABIArgInfo::getDirect(ResType);
3893 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003894 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3895 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003896
3897 if (!isAggregateTypeForABI(Ty)) {
3898 // Treat an enum type as its underlying type.
3899 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3900 Ty = EnumTy->getDecl()->getIntegerType();
3901
Tim Northovera2ee4332014-03-29 15:09:45 +00003902 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3903 ? ABIArgInfo::getExtend()
3904 : ABIArgInfo::getDirect());
3905 }
3906
3907 // Structures with either a non-trivial destructor or a non-trivial
3908 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003909 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003910 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003911 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003912 }
3913
3914 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3915 // elsewhere for GNU compatibility.
3916 if (isEmptyRecord(getContext(), Ty, true)) {
3917 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3918 return ABIArgInfo::getIgnore();
3919
Tim Northovera2ee4332014-03-29 15:09:45 +00003920 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3921 }
3922
3923 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003924 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003925 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003926 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00003927 return ABIArgInfo::getDirect(
3928 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00003929 }
3930
3931 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3932 uint64_t Size = getContext().getTypeSize(Ty);
3933 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003934 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00003935 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00003936
Tim Northovera2ee4332014-03-29 15:09:45 +00003937 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3938 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003939 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003940 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3941 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3942 }
3943 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3944 }
3945
Tim Northovera2ee4332014-03-29 15:09:45 +00003946 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3947}
3948
Tim Northover573cbee2014-05-24 12:52:07 +00003949ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003950 if (RetTy->isVoidType())
3951 return ABIArgInfo::getIgnore();
3952
3953 // Large vector types should be returned via memory.
3954 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3955 return ABIArgInfo::getIndirect(0);
3956
3957 if (!isAggregateTypeForABI(RetTy)) {
3958 // Treat an enum type as its underlying type.
3959 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3960 RetTy = EnumTy->getDecl()->getIntegerType();
3961
Tim Northover4dab6982014-04-18 13:46:08 +00003962 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3963 ? ABIArgInfo::getExtend()
3964 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003965 }
3966
Tim Northovera2ee4332014-03-29 15:09:45 +00003967 if (isEmptyRecord(getContext(), RetTy, true))
3968 return ABIArgInfo::getIgnore();
3969
Craig Topper8a13c412014-05-21 05:09:00 +00003970 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003971 uint64_t Members = 0;
3972 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00003973 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3974 return ABIArgInfo::getDirect();
3975
3976 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3977 uint64_t Size = getContext().getTypeSize(RetTy);
3978 if (Size <= 128) {
3979 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3980 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3981 }
3982
3983 return ABIArgInfo::getIndirect(0);
3984}
3985
Tim Northover573cbee2014-05-24 12:52:07 +00003986/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3987bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003988 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3989 // Check whether VT is legal.
3990 unsigned NumElements = VT->getNumElements();
3991 uint64_t Size = getContext().getTypeSize(VT);
3992 // NumElements should be power of 2 between 1 and 16.
3993 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3994 return true;
3995 return Size != 64 && (Size != 128 || NumElements == 1);
3996 }
3997 return false;
3998}
3999
Reid Klecknere9f6a712014-10-31 17:10:41 +00004000bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4001 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4002 // point type or a short-vector type. This is the same as the 32-bit ABI,
4003 // but with the difference that any floating-point type is allowed,
4004 // including __fp16.
4005 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4006 if (BT->isFloatingPoint())
4007 return true;
4008 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4009 unsigned VecSize = getContext().getTypeSize(VT);
4010 if (VecSize == 64 || VecSize == 128)
4011 return true;
4012 }
4013 return false;
4014}
4015
4016bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4017 uint64_t Members) const {
4018 return Members <= 4;
4019}
4020
Tim Northoverb047bfa2014-11-27 21:02:49 +00004021llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4022 QualType Ty,
4023 CodeGenFunction &CGF) const {
4024 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004025 bool IsIndirect = AI.isIndirect();
4026
Tim Northoverb047bfa2014-11-27 21:02:49 +00004027 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4028 if (IsIndirect)
4029 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4030 else if (AI.getCoerceToType())
4031 BaseTy = AI.getCoerceToType();
4032
4033 unsigned NumRegs = 1;
4034 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4035 BaseTy = ArrTy->getElementType();
4036 NumRegs = ArrTy->getNumElements();
4037 }
4038 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4039
Tim Northovera2ee4332014-03-29 15:09:45 +00004040 // The AArch64 va_list type and handling is specified in the Procedure Call
4041 // Standard, section B.4:
4042 //
4043 // struct {
4044 // void *__stack;
4045 // void *__gr_top;
4046 // void *__vr_top;
4047 // int __gr_offs;
4048 // int __vr_offs;
4049 // };
4050
4051 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4052 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4053 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4054 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4055 auto &Ctx = CGF.getContext();
4056
Craig Topper8a13c412014-05-21 05:09:00 +00004057 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004058 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004059 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4060 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004061 // 3 is the field number of __gr_offs
4062 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4063 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4064 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004065 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004066 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004067 // 4 is the field number of __vr_offs.
4068 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4069 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4070 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004071 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004072 }
4073
4074 //=======================================
4075 // Find out where argument was passed
4076 //=======================================
4077
4078 // If reg_offs >= 0 we're already using the stack for this type of
4079 // argument. We don't want to keep updating reg_offs (in case it overflows,
4080 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4081 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004082 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004083 UsingStack = CGF.Builder.CreateICmpSGE(
4084 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4085
4086 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4087
4088 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004089 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004090 CGF.EmitBlock(MaybeRegBlock);
4091
4092 // Integer arguments may need to correct register alignment (for example a
4093 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4094 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004095 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004096 int Align = Ctx.getTypeAlign(Ty) / 8;
4097
4098 reg_offs = CGF.Builder.CreateAdd(
4099 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4100 "align_regoffs");
4101 reg_offs = CGF.Builder.CreateAnd(
4102 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4103 "aligned_regoffs");
4104 }
4105
4106 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004107 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004108 NewOffset = CGF.Builder.CreateAdd(
4109 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4110 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4111
4112 // Now we're in a position to decide whether this argument really was in
4113 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004114 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004115 InRegs = CGF.Builder.CreateICmpSLE(
4116 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4117
4118 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4119
4120 //=======================================
4121 // Argument was in registers
4122 //=======================================
4123
4124 // Now we emit the code for if the argument was originally passed in
4125 // registers. First start the appropriate block:
4126 CGF.EmitBlock(InRegBlock);
4127
Craig Topper8a13c412014-05-21 05:09:00 +00004128 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004129 reg_top_p =
4130 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4131 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4132 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004133 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004134 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4135
4136 if (IsIndirect) {
4137 // If it's been passed indirectly (actually a struct), whatever we find from
4138 // stored registers or on the stack will actually be a struct **.
4139 MemTy = llvm::PointerType::getUnqual(MemTy);
4140 }
4141
Craig Topper8a13c412014-05-21 05:09:00 +00004142 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004143 uint64_t NumMembers = 0;
4144 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004145 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004146 // Homogeneous aggregates passed in registers will have their elements split
4147 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4148 // qN+1, ...). We reload and store into a temporary local variable
4149 // contiguously.
4150 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4151 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4152 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4153 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4154 int Offset = 0;
4155
4156 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4157 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4158 for (unsigned i = 0; i < NumMembers; ++i) {
4159 llvm::Value *BaseOffset =
4160 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4161 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4162 LoadAddr = CGF.Builder.CreateBitCast(
4163 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4164 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4165
4166 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4167 CGF.Builder.CreateStore(Elem, StoreAddr);
4168 }
4169
4170 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4171 } else {
4172 // Otherwise the object is contiguous in memory
4173 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004174 if (CGF.CGM.getDataLayout().isBigEndian() &&
4175 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004176 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4177 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4178 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4179
4180 BaseAddr = CGF.Builder.CreateAdd(
4181 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4182
4183 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4184 }
4185
4186 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4187 }
4188
4189 CGF.EmitBranch(ContBlock);
4190
4191 //=======================================
4192 // Argument was on the stack
4193 //=======================================
4194 CGF.EmitBlock(OnStackBlock);
4195
Craig Topper8a13c412014-05-21 05:09:00 +00004196 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004197 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4198 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4199
4200 // Again, stack arguments may need realigmnent. In this case both integer and
4201 // floating-point ones might be affected.
4202 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4203 int Align = Ctx.getTypeAlign(Ty) / 8;
4204
4205 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4206
4207 OnStackAddr = CGF.Builder.CreateAdd(
4208 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4209 "align_stack");
4210 OnStackAddr = CGF.Builder.CreateAnd(
4211 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4212 "align_stack");
4213
4214 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4215 }
4216
4217 uint64_t StackSize;
4218 if (IsIndirect)
4219 StackSize = 8;
4220 else
4221 StackSize = Ctx.getTypeSize(Ty) / 8;
4222
4223 // All stack slots are 8 bytes
4224 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4225
4226 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4227 llvm::Value *NewStack =
4228 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4229
4230 // Write the new value of __stack for the next call to va_arg
4231 CGF.Builder.CreateStore(NewStack, stack_p);
4232
4233 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4234 Ctx.getTypeSize(Ty) < 64) {
4235 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4236 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4237
4238 OnStackAddr = CGF.Builder.CreateAdd(
4239 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4240
4241 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4242 }
4243
4244 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4245
4246 CGF.EmitBranch(ContBlock);
4247
4248 //=======================================
4249 // Tidy up
4250 //=======================================
4251 CGF.EmitBlock(ContBlock);
4252
4253 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4254 ResAddr->addIncoming(RegAddr, InRegBlock);
4255 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4256
4257 if (IsIndirect)
4258 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4259
4260 return ResAddr;
4261}
4262
Tim Northover573cbee2014-05-24 12:52:07 +00004263llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004264 CodeGenFunction &CGF) const {
4265 // We do not support va_arg for aggregates or illegal vector types.
4266 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4267 // other cases.
4268 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004269 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004270
4271 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4272 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4273
Craig Topper8a13c412014-05-21 05:09:00 +00004274 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004275 uint64_t Members = 0;
4276 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004277
4278 bool isIndirect = false;
4279 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4280 // be passed indirectly.
4281 if (Size > 16 && !isHA) {
4282 isIndirect = true;
4283 Size = 8;
4284 Align = 8;
4285 }
4286
4287 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4288 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4289
4290 CGBuilderTy &Builder = CGF.Builder;
4291 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4292 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4293
4294 if (isEmptyRecord(getContext(), Ty, true)) {
4295 // These are ignored for parameter passing purposes.
4296 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4297 return Builder.CreateBitCast(Addr, PTy);
4298 }
4299
4300 const uint64_t MinABIAlign = 8;
4301 if (Align > MinABIAlign) {
4302 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4303 Addr = Builder.CreateGEP(Addr, Offset);
4304 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4305 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4306 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4307 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4308 }
4309
4310 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4311 llvm::Value *NextAddr = Builder.CreateGEP(
4312 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4313 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4314
4315 if (isIndirect)
4316 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4317 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4318 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4319
4320 return AddrTyped;
4321}
4322
4323//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004324// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004325//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004326
4327namespace {
4328
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004329class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004330public:
4331 enum ABIKind {
4332 APCS = 0,
4333 AAPCS = 1,
4334 AAPCS_VFP
4335 };
4336
4337private:
4338 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004339 mutable int VFPRegs[16];
4340 const unsigned NumVFPs;
4341 const unsigned NumGPRs;
4342 mutable unsigned AllocatedGPRs;
4343 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004344
4345public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004346 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4347 NumVFPs(16), NumGPRs(4) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004348 setCCs();
Oliver Stannard405bded2014-02-11 09:25:50 +00004349 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004350 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004351
John McCall3480ef22011-08-30 01:42:09 +00004352 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004353 switch (getTarget().getTriple().getEnvironment()) {
4354 case llvm::Triple::Android:
4355 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004356 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004357 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004358 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004359 return true;
4360 default:
4361 return false;
4362 }
John McCall3480ef22011-08-30 01:42:09 +00004363 }
4364
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004365 bool isEABIHF() const {
4366 switch (getTarget().getTriple().getEnvironment()) {
4367 case llvm::Triple::EABIHF:
4368 case llvm::Triple::GNUEABIHF:
4369 return true;
4370 default:
4371 return false;
4372 }
4373 }
4374
Daniel Dunbar020daa92009-09-12 01:00:39 +00004375 ABIKind getABIKind() const { return Kind; }
4376
Tim Northovera484bc02013-10-01 14:34:25 +00004377private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004378 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004379 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004380 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004381 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004382
Reid Klecknere9f6a712014-10-31 17:10:41 +00004383 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4384 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4385 uint64_t Members) const override;
4386
Craig Topper4f12f102014-03-12 06:41:41 +00004387 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004388
Craig Topper4f12f102014-03-12 06:41:41 +00004389 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4390 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004391
4392 llvm::CallingConv::ID getLLVMDefaultCC() const;
4393 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004394 void setCCs();
Oliver Stannard405bded2014-02-11 09:25:50 +00004395
4396 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4397 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4398 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004399};
4400
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004401class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4402public:
Chris Lattner2b037972010-07-29 02:01:43 +00004403 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4404 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004405
John McCall3480ef22011-08-30 01:42:09 +00004406 const ARMABIInfo &getABIInfo() const {
4407 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4408 }
4409
Craig Topper4f12f102014-03-12 06:41:41 +00004410 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004411 return 13;
4412 }
Roman Divackyc1617352011-05-18 19:36:54 +00004413
Craig Topper4f12f102014-03-12 06:41:41 +00004414 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004415 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4416 }
4417
Roman Divackyc1617352011-05-18 19:36:54 +00004418 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004419 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004420 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004421
4422 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004423 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004424 return false;
4425 }
John McCall3480ef22011-08-30 01:42:09 +00004426
Craig Topper4f12f102014-03-12 06:41:41 +00004427 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004428 if (getABIInfo().isEABI()) return 88;
4429 return TargetCodeGenInfo::getSizeOfUnwindException();
4430 }
Tim Northovera484bc02013-10-01 14:34:25 +00004431
4432 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004433 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004434 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4435 if (!FD)
4436 return;
4437
4438 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4439 if (!Attr)
4440 return;
4441
4442 const char *Kind;
4443 switch (Attr->getInterrupt()) {
4444 case ARMInterruptAttr::Generic: Kind = ""; break;
4445 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4446 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4447 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4448 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4449 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4450 }
4451
4452 llvm::Function *Fn = cast<llvm::Function>(GV);
4453
4454 Fn->addFnAttr("interrupt", Kind);
4455
4456 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4457 return;
4458
4459 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4460 // however this is not necessarily true on taking any interrupt. Instruct
4461 // the backend to perform a realignment as part of the function prologue.
4462 llvm::AttrBuilder B;
4463 B.addStackAlignmentAttr(8);
4464 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4465 llvm::AttributeSet::get(CGM.getLLVMContext(),
4466 llvm::AttributeSet::FunctionIndex,
4467 B));
4468 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004469};
4470
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004471class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4472 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4473 CodeGen::CodeGenModule &CGM) const;
4474
4475public:
4476 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4477 : ARMTargetCodeGenInfo(CGT, K) {}
4478
4479 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4480 CodeGen::CodeGenModule &CGM) const override;
4481};
4482
4483void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4484 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4485 if (!isa<FunctionDecl>(D))
4486 return;
4487 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4488 return;
4489
4490 llvm::Function *F = cast<llvm::Function>(GV);
4491 F->addFnAttr("stack-probe-size",
4492 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4493}
4494
4495void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4496 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4497 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4498 addStackProbeSizeTargetAttribute(D, GV, CGM);
4499}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004500}
4501
Chris Lattner22326a12010-07-29 02:31:05 +00004502void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004503 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004504 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004505 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4506 // VFP registers of the appropriate type unallocated then the argument is
4507 // allocated to the lowest-numbered sequence of such registers.
4508 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4509 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004510 resetAllocatedRegs();
4511
Reid Kleckner40ca9132014-05-13 22:05:45 +00004512 if (getCXXABI().classifyReturnType(FI)) {
4513 if (FI.getReturnInfo().isIndirect())
4514 markAllocatedGPRs(1, 1);
4515 } else {
4516 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4517 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004518 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004519 unsigned PreAllocationVFPs = AllocatedVFPs;
4520 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004521 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004522 // 6.1.2.3 There is one VFP co-processor register class using registers
4523 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004524 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004525
4526 // If we have allocated some arguments onto the stack (due to running
4527 // out of VFP registers), we cannot split an argument between GPRs and
4528 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004529 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004530 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4531 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004532 // We do not have to do this if the argument is being passed ByVal, as the
4533 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004534 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004535 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4536 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4537 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004538 llvm::Type *PaddingTy = llvm::ArrayType::get(
4539 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004540 if (I.info.canHaveCoerceToType()) {
Tim Northover5a1558e2014-11-07 22:30:50 +00004541 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */,
4542 0 /* offset */, PaddingTy, true);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004543 } else {
4544 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Tim Northover5a1558e2014-11-07 22:30:50 +00004545 PaddingTy, true);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004546 }
Manman Ren2a523d82012-10-30 23:21:41 +00004547 }
4548 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004549
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004550 // Always honor user-specified calling convention.
4551 if (FI.getCallingConvention() != llvm::CallingConv::C)
4552 return;
4553
John McCall882987f2013-02-28 19:01:20 +00004554 llvm::CallingConv::ID cc = getRuntimeCC();
4555 if (cc != llvm::CallingConv::C)
4556 FI.setEffectiveCallingConvention(cc);
4557}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004558
John McCall882987f2013-02-28 19:01:20 +00004559/// Return the default calling convention that LLVM will use.
4560llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4561 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004562 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004563 return llvm::CallingConv::ARM_AAPCS_VFP;
4564 else if (isEABI())
4565 return llvm::CallingConv::ARM_AAPCS;
4566 else
4567 return llvm::CallingConv::ARM_APCS;
4568}
4569
4570/// Return the calling convention that our ABI would like us to use
4571/// as the C calling convention.
4572llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004573 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004574 case APCS: return llvm::CallingConv::ARM_APCS;
4575 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4576 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004577 }
John McCall882987f2013-02-28 19:01:20 +00004578 llvm_unreachable("bad ABI kind");
4579}
4580
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004581void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004582 assert(getRuntimeCC() == llvm::CallingConv::C);
4583
4584 // Don't muddy up the IR with a ton of explicit annotations if
4585 // they'd just match what LLVM will infer from the triple.
4586 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4587 if (abiCC != getLLVMDefaultCC())
4588 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004589
4590 BuiltinCC = (getABIKind() == APCS ?
4591 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004592}
4593
Manman Renb505d332012-10-31 19:02:26 +00004594/// markAllocatedVFPs - update VFPRegs according to the alignment and
4595/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004596void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4597 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004598 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004599 if (AllocatedVFPs >= 16) {
4600 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4601 // the stack.
4602 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004603 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004604 }
Manman Renb505d332012-10-31 19:02:26 +00004605 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4606 // VFP registers of the appropriate type unallocated then the argument is
4607 // allocated to the lowest-numbered sequence of such registers.
4608 for (unsigned I = 0; I < 16; I += Alignment) {
4609 bool FoundSlot = true;
4610 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4611 if (J >= 16 || VFPRegs[J]) {
4612 FoundSlot = false;
4613 break;
4614 }
4615 if (FoundSlot) {
4616 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4617 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004618 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004619 return;
4620 }
4621 }
4622 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4623 // unallocated are marked as unavailable.
4624 for (unsigned I = 0; I < 16; I++)
4625 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004626 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004627}
4628
Oliver Stannard405bded2014-02-11 09:25:50 +00004629/// Update AllocatedGPRs to record the number of general purpose registers
4630/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4631/// this represents arguments being stored on the stack.
4632void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004633 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004634 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4635
4636 if (Alignment == 2 && AllocatedGPRs & 0x1)
4637 AllocatedGPRs += 1;
4638
4639 AllocatedGPRs += NumRequired;
4640}
4641
4642void ARMABIInfo::resetAllocatedRegs(void) const {
4643 AllocatedGPRs = 0;
4644 AllocatedVFPs = 0;
4645 for (unsigned i = 0; i < NumVFPs; ++i)
4646 VFPRegs[i] = 0;
4647}
4648
James Molloy6f244b62014-05-09 16:21:39 +00004649ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004650 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004651 // We update number of allocated VFPs according to
4652 // 6.1.2.1 The following argument types are VFP CPRCs:
4653 // A single-precision floating-point type (including promoted
4654 // half-precision types); A double-precision floating-point type;
4655 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4656 // with a Base Type of a single- or double-precision floating-point type,
4657 // 64-bit containerized vectors or 128-bit containerized vectors with one
4658 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004659 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004660
Reid Klecknerb1be6832014-11-15 01:41:41 +00004661 Ty = useFirstFieldIfTransparentUnion(Ty);
4662
Manman Renfef9e312012-10-16 19:18:39 +00004663 // Handle illegal vector types here.
4664 if (isIllegalVectorType(Ty)) {
4665 uint64_t Size = getContext().getTypeSize(Ty);
4666 if (Size <= 32) {
4667 llvm::Type *ResType =
4668 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004669 markAllocatedGPRs(1, 1);
Tim Northover5a1558e2014-11-07 22:30:50 +00004670 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004671 }
4672 if (Size == 64) {
4673 llvm::Type *ResType = llvm::VectorType::get(
4674 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004675 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4676 markAllocatedGPRs(2, 2);
4677 } else {
4678 markAllocatedVFPs(2, 2);
4679 IsCPRC = true;
4680 }
Tim Northover5a1558e2014-11-07 22:30:50 +00004681 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004682 }
4683 if (Size == 128) {
4684 llvm::Type *ResType = llvm::VectorType::get(
4685 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004686 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4687 markAllocatedGPRs(2, 4);
4688 } else {
4689 markAllocatedVFPs(4, 4);
4690 IsCPRC = true;
4691 }
Tim Northover5a1558e2014-11-07 22:30:50 +00004692 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004693 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004694 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004695 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4696 }
Manman Renb505d332012-10-31 19:02:26 +00004697 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004698 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4699 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4700 uint64_t Size = getContext().getTypeSize(VT);
4701 // Size of a legal vector should be power of 2 and above 64.
4702 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4703 IsCPRC = true;
4704 }
Manman Ren2a523d82012-10-30 23:21:41 +00004705 }
Manman Renb505d332012-10-31 19:02:26 +00004706 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004707 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4708 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4709 if (BT->getKind() == BuiltinType::Half ||
4710 BT->getKind() == BuiltinType::Float) {
4711 markAllocatedVFPs(1, 1);
4712 IsCPRC = true;
4713 }
4714 if (BT->getKind() == BuiltinType::Double ||
4715 BT->getKind() == BuiltinType::LongDouble) {
4716 markAllocatedVFPs(2, 2);
4717 IsCPRC = true;
4718 }
4719 }
Manman Ren2a523d82012-10-30 23:21:41 +00004720 }
Manman Renfef9e312012-10-16 19:18:39 +00004721
John McCalla1dee5302010-08-22 10:59:02 +00004722 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004723 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004724 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004725 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004726 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004727
Oliver Stannard405bded2014-02-11 09:25:50 +00004728 unsigned Size = getContext().getTypeSize(Ty);
4729 if (!IsCPRC)
4730 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Tim Northover5a1558e2014-11-07 22:30:50 +00004731 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4732 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004733 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004734
Oliver Stannard405bded2014-02-11 09:25:50 +00004735 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4736 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004737 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004738 }
Tim Northover1060eae2013-06-21 22:49:34 +00004739
Daniel Dunbar09d33622009-09-14 21:54:03 +00004740 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004741 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004742 return ABIArgInfo::getIgnore();
4743
Tim Northover5a1558e2014-11-07 22:30:50 +00004744 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004745 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4746 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004747 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004748 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004749 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004750 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004751 // Base can be a floating-point or a vector.
4752 if (Base->isVectorType()) {
4753 // ElementSize is in number of floats.
4754 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004755 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004756 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004757 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004758 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004759 else {
4760 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4761 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004762 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004763 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004764 IsCPRC = true;
Tim Northover5a1558e2014-11-07 22:30:50 +00004765 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004766 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004767 }
4768
Manman Ren6c30e132012-08-13 21:23:55 +00004769 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004770 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4771 // most 8-byte. We realign the indirect argument if type alignment is bigger
4772 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004773 uint64_t ABIAlign = 4;
4774 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4775 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4776 getABIKind() == ARMABIInfo::AAPCS)
4777 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004778 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004779 // Update Allocated GPRs. Since this is only used when the size of the
4780 // argument is greater than 64 bytes, this will always use up any available
4781 // registers (of which there are 4). We also don't care about getting the
4782 // alignment right, because general-purpose registers cannot be back-filled.
4783 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004784 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004785 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004786 }
4787
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004788 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004789 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004790 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004791 // FIXME: Try to match the types of the arguments more accurately where
4792 // we can.
4793 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004794 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4795 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004796 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004797 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004798 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4799 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004800 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004801 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004802
Tim Northover5a1558e2014-11-07 22:30:50 +00004803 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004804}
4805
Chris Lattner458b2aa2010-07-29 02:16:43 +00004806static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004807 llvm::LLVMContext &VMContext) {
4808 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4809 // is called integer-like if its size is less than or equal to one word, and
4810 // the offset of each of its addressable sub-fields is zero.
4811
4812 uint64_t Size = Context.getTypeSize(Ty);
4813
4814 // Check that the type fits in a word.
4815 if (Size > 32)
4816 return false;
4817
4818 // FIXME: Handle vector types!
4819 if (Ty->isVectorType())
4820 return false;
4821
Daniel Dunbard53bac72009-09-14 02:20:34 +00004822 // Float types are never treated as "integer like".
4823 if (Ty->isRealFloatingType())
4824 return false;
4825
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004826 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004827 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004828 return true;
4829
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004830 // Small complex integer types are "integer like".
4831 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4832 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004833
4834 // Single element and zero sized arrays should be allowed, by the definition
4835 // above, but they are not.
4836
4837 // Otherwise, it must be a record type.
4838 const RecordType *RT = Ty->getAs<RecordType>();
4839 if (!RT) return false;
4840
4841 // Ignore records with flexible arrays.
4842 const RecordDecl *RD = RT->getDecl();
4843 if (RD->hasFlexibleArrayMember())
4844 return false;
4845
4846 // Check that all sub-fields are at offset 0, and are themselves "integer
4847 // like".
4848 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4849
4850 bool HadField = false;
4851 unsigned idx = 0;
4852 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4853 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004854 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004855
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004856 // Bit-fields are not addressable, we only need to verify they are "integer
4857 // like". We still have to disallow a subsequent non-bitfield, for example:
4858 // struct { int : 0; int x }
4859 // is non-integer like according to gcc.
4860 if (FD->isBitField()) {
4861 if (!RD->isUnion())
4862 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004863
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004864 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4865 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004866
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004867 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004868 }
4869
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004870 // Check if this field is at offset 0.
4871 if (Layout.getFieldOffset(idx) != 0)
4872 return false;
4873
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004874 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4875 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004876
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004877 // Only allow at most one field in a structure. This doesn't match the
4878 // wording above, but follows gcc in situations with a field following an
4879 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004880 if (!RD->isUnion()) {
4881 if (HadField)
4882 return false;
4883
4884 HadField = true;
4885 }
4886 }
4887
4888 return true;
4889}
4890
Oliver Stannard405bded2014-02-11 09:25:50 +00004891ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4892 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004893 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004894
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004895 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004896 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004897
Daniel Dunbar19964db2010-09-23 01:54:32 +00004898 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004899 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4900 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004901 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004902 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004903
John McCalla1dee5302010-08-22 10:59:02 +00004904 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004905 // Treat an enum type as its underlying type.
4906 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4907 RetTy = EnumTy->getDecl()->getIntegerType();
4908
Tim Northover5a1558e2014-11-07 22:30:50 +00004909 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4910 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004911 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004912
4913 // Are we following APCS?
4914 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004915 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004916 return ABIArgInfo::getIgnore();
4917
Daniel Dunbareedf1512010-02-01 23:31:19 +00004918 // Complex types are all returned as packed integers.
4919 //
4920 // FIXME: Consider using 2 x vector types if the back end handles them
4921 // correctly.
4922 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004923 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4924 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004925
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004926 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004927 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004928 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004929 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004930 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004931 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004932 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004933 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4934 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004935 }
4936
4937 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004938 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004939 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004940 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004941
4942 // Otherwise this is an AAPCS variant.
4943
Chris Lattner458b2aa2010-07-29 02:16:43 +00004944 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004945 return ABIArgInfo::getIgnore();
4946
Bob Wilson1d9269a2011-11-02 04:51:36 +00004947 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004948 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004949 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004950 uint64_t Members;
4951 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004952 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004953 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004954 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004955 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004956 }
4957
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004958 // Aggregates <= 4 bytes are returned in r0; other aggregates
4959 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004960 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004961 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004962 if (getDataLayout().isBigEndian())
4963 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004964 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004965
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004966 // Return in the smallest viable integer type.
4967 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004968 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004969 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004970 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4971 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004972 }
4973
Oliver Stannard405bded2014-02-11 09:25:50 +00004974 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004975 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004976}
4977
Manman Renfef9e312012-10-16 19:18:39 +00004978/// isIllegalVector - check whether Ty is an illegal vector type.
4979bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4980 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4981 // Check whether VT is legal.
4982 unsigned NumElements = VT->getNumElements();
4983 uint64_t Size = getContext().getTypeSize(VT);
4984 // NumElements should be power of 2.
4985 if ((NumElements & (NumElements - 1)) != 0)
4986 return true;
4987 // Size should be greater than 32 bits.
4988 return Size <= 32;
4989 }
4990 return false;
4991}
4992
Reid Klecknere9f6a712014-10-31 17:10:41 +00004993bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4994 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4995 // double, or 64-bit or 128-bit vectors.
4996 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4997 if (BT->getKind() == BuiltinType::Float ||
4998 BT->getKind() == BuiltinType::Double ||
4999 BT->getKind() == BuiltinType::LongDouble)
5000 return true;
5001 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5002 unsigned VecSize = getContext().getTypeSize(VT);
5003 if (VecSize == 64 || VecSize == 128)
5004 return true;
5005 }
5006 return false;
5007}
5008
5009bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5010 uint64_t Members) const {
5011 return Members <= 4;
5012}
5013
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005014llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00005015 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005016 llvm::Type *BP = CGF.Int8PtrTy;
5017 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005018
5019 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00005020 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005021 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00005022
Tim Northover1711cc92013-06-21 23:05:33 +00005023 if (isEmptyRecord(getContext(), Ty, true)) {
5024 // These are ignored for parameter passing purposes.
5025 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5026 return Builder.CreateBitCast(Addr, PTy);
5027 }
5028
Manman Rencca54d02012-10-16 19:01:37 +00005029 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00005030 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00005031 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00005032
5033 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5034 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00005035 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5036 getABIKind() == ARMABIInfo::AAPCS)
5037 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5038 else
5039 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00005040 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5041 if (isIllegalVectorType(Ty) && Size > 16) {
5042 IsIndirect = true;
5043 Size = 4;
5044 TyAlign = 4;
5045 }
Manman Rencca54d02012-10-16 19:01:37 +00005046
5047 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005048 if (TyAlign > 4) {
5049 assert((TyAlign & (TyAlign - 1)) == 0 &&
5050 "Alignment is not power of 2!");
5051 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5052 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5053 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005054 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005055 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005056
5057 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005058 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005059 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005060 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005061 "ap.next");
5062 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5063
Manman Renfef9e312012-10-16 19:18:39 +00005064 if (IsIndirect)
5065 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005066 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005067 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5068 // may not be correctly aligned for the vector type. We create an aligned
5069 // temporary space and copy the content over from ap.cur to the temporary
5070 // space. This is necessary if the natural alignment of the type is greater
5071 // than the ABI alignment.
5072 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5073 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5074 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5075 "var.align");
5076 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5077 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5078 Builder.CreateMemCpy(Dst, Src,
5079 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5080 TyAlign, false);
5081 Addr = AlignedTemp; //The content is in aligned location.
5082 }
5083 llvm::Type *PTy =
5084 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5085 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5086
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005087 return AddrTyped;
5088}
5089
Chris Lattner0cf24192010-06-28 20:05:43 +00005090//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005091// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005092//===----------------------------------------------------------------------===//
5093
5094namespace {
5095
Justin Holewinski83e96682012-05-24 17:43:12 +00005096class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005097public:
Justin Holewinski36837432013-03-30 14:38:24 +00005098 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005099
5100 ABIArgInfo classifyReturnType(QualType RetTy) const;
5101 ABIArgInfo classifyArgumentType(QualType Ty) const;
5102
Craig Topper4f12f102014-03-12 06:41:41 +00005103 void computeInfo(CGFunctionInfo &FI) const override;
5104 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5105 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005106};
5107
Justin Holewinski83e96682012-05-24 17:43:12 +00005108class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005109public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005110 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5111 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005112
5113 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5114 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005115private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005116 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5117 // resulting MDNode to the nvvm.annotations MDNode.
5118 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005119};
5120
Justin Holewinski83e96682012-05-24 17:43:12 +00005121ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005122 if (RetTy->isVoidType())
5123 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005124
5125 // note: this is different from default ABI
5126 if (!RetTy->isScalarType())
5127 return ABIArgInfo::getDirect();
5128
5129 // Treat an enum type as its underlying type.
5130 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5131 RetTy = EnumTy->getDecl()->getIntegerType();
5132
5133 return (RetTy->isPromotableIntegerType() ?
5134 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005135}
5136
Justin Holewinski83e96682012-05-24 17:43:12 +00005137ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005138 // Treat an enum type as its underlying type.
5139 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5140 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005141
Eli Bendersky95338a02014-10-29 13:43:21 +00005142 // Return aggregates type as indirect by value
5143 if (isAggregateTypeForABI(Ty))
5144 return ABIArgInfo::getIndirect(0, /* byval */ true);
5145
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005146 return (Ty->isPromotableIntegerType() ?
5147 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005148}
5149
Justin Holewinski83e96682012-05-24 17:43:12 +00005150void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005151 if (!getCXXABI().classifyReturnType(FI))
5152 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005153 for (auto &I : FI.arguments())
5154 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005155
5156 // Always honor user-specified calling convention.
5157 if (FI.getCallingConvention() != llvm::CallingConv::C)
5158 return;
5159
John McCall882987f2013-02-28 19:01:20 +00005160 FI.setEffectiveCallingConvention(getRuntimeCC());
5161}
5162
Justin Holewinski83e96682012-05-24 17:43:12 +00005163llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5164 CodeGenFunction &CFG) const {
5165 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005166}
5167
Justin Holewinski83e96682012-05-24 17:43:12 +00005168void NVPTXTargetCodeGenInfo::
5169SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5170 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005171 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5172 if (!FD) return;
5173
5174 llvm::Function *F = cast<llvm::Function>(GV);
5175
5176 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005177 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005178 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005179 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005180 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005181 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005182 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5183 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005184 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005185 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005186 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005187 }
Justin Holewinski38031972011-10-05 17:58:44 +00005188
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005189 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005190 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005191 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005192 // __global__ functions cannot be called from the device, we do not
5193 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005194 if (FD->hasAttr<CUDAGlobalAttr>()) {
5195 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5196 addNVVMMetadata(F, "kernel", 1);
5197 }
5198 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5199 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5200 addNVVMMetadata(F, "maxntidx",
5201 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5202 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5203 // zero value from getMinBlocks either means it was not specified in
5204 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5205 // don't have to add a PTX directive.
5206 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5207 if (MinCTASM > 0) {
5208 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5209 addNVVMMetadata(F, "minctasm", MinCTASM);
5210 }
5211 }
Justin Holewinski38031972011-10-05 17:58:44 +00005212 }
5213}
5214
Eli Benderskye06a2c42014-04-15 16:57:05 +00005215void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5216 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005217 llvm::Module *M = F->getParent();
5218 llvm::LLVMContext &Ctx = M->getContext();
5219
5220 // Get "nvvm.annotations" metadata node
5221 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5222
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005223 llvm::Metadata *MDVals[] = {
5224 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5225 llvm::ConstantAsMetadata::get(
5226 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005227 // Append metadata to nvvm.annotations
5228 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5229}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005230}
5231
5232//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005233// SystemZ ABI Implementation
5234//===----------------------------------------------------------------------===//
5235
5236namespace {
5237
5238class SystemZABIInfo : public ABIInfo {
5239public:
5240 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5241
5242 bool isPromotableIntegerType(QualType Ty) const;
5243 bool isCompoundType(QualType Ty) const;
5244 bool isFPArgumentType(QualType Ty) const;
5245
5246 ABIArgInfo classifyReturnType(QualType RetTy) const;
5247 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5248
Craig Topper4f12f102014-03-12 06:41:41 +00005249 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005250 if (!getCXXABI().classifyReturnType(FI))
5251 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005252 for (auto &I : FI.arguments())
5253 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005254 }
5255
Craig Topper4f12f102014-03-12 06:41:41 +00005256 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5257 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005258};
5259
5260class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5261public:
5262 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5263 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5264};
5265
5266}
5267
5268bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5269 // Treat an enum type as its underlying type.
5270 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5271 Ty = EnumTy->getDecl()->getIntegerType();
5272
5273 // Promotable integer types are required to be promoted by the ABI.
5274 if (Ty->isPromotableIntegerType())
5275 return true;
5276
5277 // 32-bit values must also be promoted.
5278 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5279 switch (BT->getKind()) {
5280 case BuiltinType::Int:
5281 case BuiltinType::UInt:
5282 return true;
5283 default:
5284 return false;
5285 }
5286 return false;
5287}
5288
5289bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5290 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5291}
5292
5293bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5294 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5295 switch (BT->getKind()) {
5296 case BuiltinType::Float:
5297 case BuiltinType::Double:
5298 return true;
5299 default:
5300 return false;
5301 }
5302
5303 if (const RecordType *RT = Ty->getAsStructureType()) {
5304 const RecordDecl *RD = RT->getDecl();
5305 bool Found = false;
5306
5307 // If this is a C++ record, check the bases first.
5308 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005309 for (const auto &I : CXXRD->bases()) {
5310 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005311
5312 // Empty bases don't affect things either way.
5313 if (isEmptyRecord(getContext(), Base, true))
5314 continue;
5315
5316 if (Found)
5317 return false;
5318 Found = isFPArgumentType(Base);
5319 if (!Found)
5320 return false;
5321 }
5322
5323 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005324 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005325 // Empty bitfields don't affect things either way.
5326 // Unlike isSingleElementStruct(), empty structure and array fields
5327 // do count. So do anonymous bitfields that aren't zero-sized.
5328 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5329 return true;
5330
5331 // Unlike isSingleElementStruct(), arrays do not count.
5332 // Nested isFPArgumentType structures still do though.
5333 if (Found)
5334 return false;
5335 Found = isFPArgumentType(FD->getType());
5336 if (!Found)
5337 return false;
5338 }
5339
5340 // Unlike isSingleElementStruct(), trailing padding is allowed.
5341 // An 8-byte aligned struct s { float f; } is passed as a double.
5342 return Found;
5343 }
5344
5345 return false;
5346}
5347
5348llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5349 CodeGenFunction &CGF) const {
5350 // Assume that va_list type is correct; should be pointer to LLVM type:
5351 // struct {
5352 // i64 __gpr;
5353 // i64 __fpr;
5354 // i8 *__overflow_arg_area;
5355 // i8 *__reg_save_area;
5356 // };
5357
5358 // Every argument occupies 8 bytes and is passed by preference in either
5359 // GPRs or FPRs.
5360 Ty = CGF.getContext().getCanonicalType(Ty);
5361 ABIArgInfo AI = classifyArgumentType(Ty);
5362 bool InFPRs = isFPArgumentType(Ty);
5363
5364 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5365 bool IsIndirect = AI.isIndirect();
5366 unsigned UnpaddedBitSize;
5367 if (IsIndirect) {
5368 APTy = llvm::PointerType::getUnqual(APTy);
5369 UnpaddedBitSize = 64;
5370 } else
5371 UnpaddedBitSize = getContext().getTypeSize(Ty);
5372 unsigned PaddedBitSize = 64;
5373 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5374
5375 unsigned PaddedSize = PaddedBitSize / 8;
5376 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5377
5378 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5379 if (InFPRs) {
5380 MaxRegs = 4; // Maximum of 4 FPR arguments
5381 RegCountField = 1; // __fpr
5382 RegSaveIndex = 16; // save offset for f0
5383 RegPadding = 0; // floats are passed in the high bits of an FPR
5384 } else {
5385 MaxRegs = 5; // Maximum of 5 GPR arguments
5386 RegCountField = 0; // __gpr
5387 RegSaveIndex = 2; // save offset for r2
5388 RegPadding = Padding; // values are passed in the low bits of a GPR
5389 }
5390
5391 llvm::Value *RegCountPtr =
5392 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5393 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5394 llvm::Type *IndexTy = RegCount->getType();
5395 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5396 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005397 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005398
5399 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5400 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5401 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5402 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5403
5404 // Emit code to load the value if it was passed in registers.
5405 CGF.EmitBlock(InRegBlock);
5406
5407 // Work out the address of an argument register.
5408 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5409 llvm::Value *ScaledRegCount =
5410 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5411 llvm::Value *RegBase =
5412 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5413 llvm::Value *RegOffset =
5414 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5415 llvm::Value *RegSaveAreaPtr =
5416 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5417 llvm::Value *RegSaveArea =
5418 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5419 llvm::Value *RawRegAddr =
5420 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5421 llvm::Value *RegAddr =
5422 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5423
5424 // Update the register count
5425 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5426 llvm::Value *NewRegCount =
5427 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5428 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5429 CGF.EmitBranch(ContBlock);
5430
5431 // Emit code to load the value if it was passed in memory.
5432 CGF.EmitBlock(InMemBlock);
5433
5434 // Work out the address of a stack argument.
5435 llvm::Value *OverflowArgAreaPtr =
5436 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5437 llvm::Value *OverflowArgArea =
5438 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5439 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5440 llvm::Value *RawMemAddr =
5441 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5442 llvm::Value *MemAddr =
5443 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5444
5445 // Update overflow_arg_area_ptr pointer
5446 llvm::Value *NewOverflowArgArea =
5447 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5448 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5449 CGF.EmitBranch(ContBlock);
5450
5451 // Return the appropriate result.
5452 CGF.EmitBlock(ContBlock);
5453 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5454 ResAddr->addIncoming(RegAddr, InRegBlock);
5455 ResAddr->addIncoming(MemAddr, InMemBlock);
5456
5457 if (IsIndirect)
5458 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5459
5460 return ResAddr;
5461}
5462
Ulrich Weigand47445072013-05-06 16:26:41 +00005463ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5464 if (RetTy->isVoidType())
5465 return ABIArgInfo::getIgnore();
5466 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5467 return ABIArgInfo::getIndirect(0);
5468 return (isPromotableIntegerType(RetTy) ?
5469 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5470}
5471
5472ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5473 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005474 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005475 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5476
5477 // Integers and enums are extended to full register width.
5478 if (isPromotableIntegerType(Ty))
5479 return ABIArgInfo::getExtend();
5480
5481 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5482 uint64_t Size = getContext().getTypeSize(Ty);
5483 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005484 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005485
5486 // Handle small structures.
5487 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5488 // Structures with flexible arrays have variable length, so really
5489 // fail the size test above.
5490 const RecordDecl *RD = RT->getDecl();
5491 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005492 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005493
5494 // The structure is passed as an unextended integer, a float, or a double.
5495 llvm::Type *PassTy;
5496 if (isFPArgumentType(Ty)) {
5497 assert(Size == 32 || Size == 64);
5498 if (Size == 32)
5499 PassTy = llvm::Type::getFloatTy(getVMContext());
5500 else
5501 PassTy = llvm::Type::getDoubleTy(getVMContext());
5502 } else
5503 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5504 return ABIArgInfo::getDirect(PassTy);
5505 }
5506
5507 // Non-structure compounds are passed indirectly.
5508 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005509 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005510
Craig Topper8a13c412014-05-21 05:09:00 +00005511 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005512}
5513
5514//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005515// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005516//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005517
5518namespace {
5519
5520class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5521public:
Chris Lattner2b037972010-07-29 02:01:43 +00005522 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5523 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005524 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005525 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005526};
5527
5528}
5529
5530void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5531 llvm::GlobalValue *GV,
5532 CodeGen::CodeGenModule &M) const {
5533 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5534 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5535 // Handle 'interrupt' attribute:
5536 llvm::Function *F = cast<llvm::Function>(GV);
5537
5538 // Step 1: Set ISR calling convention.
5539 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5540
5541 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005542 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005543
5544 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005545 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005546 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5547 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005548 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005549 }
5550}
5551
Chris Lattner0cf24192010-06-28 20:05:43 +00005552//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005553// MIPS ABI Implementation. This works for both little-endian and
5554// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005555//===----------------------------------------------------------------------===//
5556
John McCall943fae92010-05-27 06:19:26 +00005557namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005558class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005559 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005560 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5561 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005562 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005563 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005564 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005565 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005566public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005567 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005568 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005569 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005570
5571 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005572 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005573 void computeInfo(CGFunctionInfo &FI) const override;
5574 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5575 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005576};
5577
John McCall943fae92010-05-27 06:19:26 +00005578class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005579 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005580public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005581 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5582 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005583 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005584
Craig Topper4f12f102014-03-12 06:41:41 +00005585 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005586 return 29;
5587 }
5588
Reed Kotler373feca2013-01-16 17:10:28 +00005589 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005590 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005591 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5592 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005593 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005594 if (FD->hasAttr<Mips16Attr>()) {
5595 Fn->addFnAttr("mips16");
5596 }
5597 else if (FD->hasAttr<NoMips16Attr>()) {
5598 Fn->addFnAttr("nomips16");
5599 }
Reed Kotler373feca2013-01-16 17:10:28 +00005600 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005601
John McCall943fae92010-05-27 06:19:26 +00005602 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005603 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005604
Craig Topper4f12f102014-03-12 06:41:41 +00005605 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005606 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005607 }
John McCall943fae92010-05-27 06:19:26 +00005608};
5609}
5610
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005611void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005612 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005613 llvm::IntegerType *IntTy =
5614 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005615
5616 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5617 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5618 ArgList.push_back(IntTy);
5619
5620 // If necessary, add one more integer type to ArgList.
5621 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5622
5623 if (R)
5624 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005625}
5626
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005627// In N32/64, an aligned double precision floating point field is passed in
5628// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005629llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005630 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5631
5632 if (IsO32) {
5633 CoerceToIntArgs(TySize, ArgList);
5634 return llvm::StructType::get(getVMContext(), ArgList);
5635 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005636
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005637 if (Ty->isComplexType())
5638 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005639
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005640 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005641
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005642 // Unions/vectors are passed in integer registers.
5643 if (!RT || !RT->isStructureOrClassType()) {
5644 CoerceToIntArgs(TySize, ArgList);
5645 return llvm::StructType::get(getVMContext(), ArgList);
5646 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005647
5648 const RecordDecl *RD = RT->getDecl();
5649 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005650 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005651
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005652 uint64_t LastOffset = 0;
5653 unsigned idx = 0;
5654 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5655
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005656 // Iterate over fields in the struct/class and check if there are any aligned
5657 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005658 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5659 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005660 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005661 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5662
5663 if (!BT || BT->getKind() != BuiltinType::Double)
5664 continue;
5665
5666 uint64_t Offset = Layout.getFieldOffset(idx);
5667 if (Offset % 64) // Ignore doubles that are not aligned.
5668 continue;
5669
5670 // Add ((Offset - LastOffset) / 64) args of type i64.
5671 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5672 ArgList.push_back(I64);
5673
5674 // Add double type.
5675 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5676 LastOffset = Offset + 64;
5677 }
5678
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005679 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5680 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005681
5682 return llvm::StructType::get(getVMContext(), ArgList);
5683}
5684
Akira Hatanakaddd66342013-10-29 18:41:15 +00005685llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5686 uint64_t Offset) const {
5687 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005688 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005689
Akira Hatanakaddd66342013-10-29 18:41:15 +00005690 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005691}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005692
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005693ABIArgInfo
5694MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005695 Ty = useFirstFieldIfTransparentUnion(Ty);
5696
Akira Hatanaka1632af62012-01-09 19:31:25 +00005697 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005698 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005699 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005700
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005701 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5702 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005703 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5704 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005705
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005706 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005707 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005708 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005709 return ABIArgInfo::getIgnore();
5710
Mark Lacey3825e832013-10-06 01:33:34 +00005711 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005712 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005713 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005714 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005715
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005716 // If we have reached here, aggregates are passed directly by coercing to
5717 // another structure type. Padding is inserted if the offset of the
5718 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005719 ABIArgInfo ArgInfo =
5720 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5721 getPaddingType(OrigOffset, CurrOffset));
5722 ArgInfo.setInReg(true);
5723 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005724 }
5725
5726 // Treat an enum type as its underlying type.
5727 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5728 Ty = EnumTy->getDecl()->getIntegerType();
5729
Daniel Sanders5b445b32014-10-24 14:42:42 +00005730 // All integral types are promoted to the GPR width.
5731 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005732 return ABIArgInfo::getExtend();
5733
Akira Hatanakaddd66342013-10-29 18:41:15 +00005734 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005735 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005736}
5737
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005738llvm::Type*
5739MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005740 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005741 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005742
Akira Hatanakab6f74432012-02-09 18:49:26 +00005743 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005744 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005745 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5746 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005747
Akira Hatanakab6f74432012-02-09 18:49:26 +00005748 // N32/64 returns struct/classes in floating point registers if the
5749 // following conditions are met:
5750 // 1. The size of the struct/class is no larger than 128-bit.
5751 // 2. The struct/class has one or two fields all of which are floating
5752 // point types.
5753 // 3. The offset of the first field is zero (this follows what gcc does).
5754 //
5755 // Any other composite results are returned in integer registers.
5756 //
5757 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5758 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5759 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005760 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005761
Akira Hatanakab6f74432012-02-09 18:49:26 +00005762 if (!BT || !BT->isFloatingPoint())
5763 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005764
David Blaikie2d7c57e2012-04-30 02:36:29 +00005765 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005766 }
5767
5768 if (b == e)
5769 return llvm::StructType::get(getVMContext(), RTList,
5770 RD->hasAttr<PackedAttr>());
5771
5772 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005773 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005774 }
5775
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005776 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005777 return llvm::StructType::get(getVMContext(), RTList);
5778}
5779
Akira Hatanakab579fe52011-06-02 00:09:17 +00005780ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005781 uint64_t Size = getContext().getTypeSize(RetTy);
5782
Daniel Sandersed39f582014-09-04 13:28:14 +00005783 if (RetTy->isVoidType())
5784 return ABIArgInfo::getIgnore();
5785
5786 // O32 doesn't treat zero-sized structs differently from other structs.
5787 // However, N32/N64 ignores zero sized return values.
5788 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005789 return ABIArgInfo::getIgnore();
5790
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005791 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005792 if (Size <= 128) {
5793 if (RetTy->isAnyComplexType())
5794 return ABIArgInfo::getDirect();
5795
Daniel Sanderse5018b62014-09-04 15:05:39 +00005796 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005797 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005798 if (!IsO32 ||
5799 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5800 ABIArgInfo ArgInfo =
5801 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5802 ArgInfo.setInReg(true);
5803 return ArgInfo;
5804 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005805 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005806
5807 return ABIArgInfo::getIndirect(0);
5808 }
5809
5810 // Treat an enum type as its underlying type.
5811 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5812 RetTy = EnumTy->getDecl()->getIntegerType();
5813
5814 return (RetTy->isPromotableIntegerType() ?
5815 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5816}
5817
5818void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005819 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005820 if (!getCXXABI().classifyReturnType(FI))
5821 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005822
5823 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005824 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005825
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005826 for (auto &I : FI.arguments())
5827 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005828}
5829
5830llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5831 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005832 llvm::Type *BP = CGF.Int8PtrTy;
5833 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005834
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005835 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5836 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005837 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005838 unsigned PtrWidth = getTarget().getPointerWidth(0);
5839 if ((Ty->isIntegerType() &&
5840 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5841 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005842 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5843 Ty->isSignedIntegerType());
5844 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005845
5846 CGBuilderTy &Builder = CGF.Builder;
5847 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5848 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005849 int64_t TypeAlign =
5850 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005851 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5852 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005853 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5854
5855 if (TypeAlign > MinABIStackAlignInBytes) {
5856 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5857 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5858 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5859 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5860 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5861 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5862 }
5863 else
5864 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5865
5866 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5867 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005868 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5869 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005870 llvm::Value *NextAddr =
5871 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5872 "ap.next");
5873 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5874
5875 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005876}
5877
John McCall943fae92010-05-27 06:19:26 +00005878bool
5879MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5880 llvm::Value *Address) const {
5881 // This information comes from gcc's implementation, which seems to
5882 // as canonical as it gets.
5883
John McCall943fae92010-05-27 06:19:26 +00005884 // Everything on MIPS is 4 bytes. Double-precision FP registers
5885 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005886 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005887
5888 // 0-31 are the general purpose registers, $0 - $31.
5889 // 32-63 are the floating-point registers, $f0 - $f31.
5890 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5891 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005892 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005893
5894 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5895 // They are one bit wide and ignored here.
5896
5897 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5898 // (coprocessor 1 is the FP unit)
5899 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5900 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5901 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005902 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005903 return false;
5904}
5905
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005906//===----------------------------------------------------------------------===//
5907// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5908// Currently subclassed only to implement custom OpenCL C function attribute
5909// handling.
5910//===----------------------------------------------------------------------===//
5911
5912namespace {
5913
5914class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5915public:
5916 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5917 : DefaultTargetCodeGenInfo(CGT) {}
5918
Craig Topper4f12f102014-03-12 06:41:41 +00005919 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5920 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005921};
5922
5923void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5924 llvm::GlobalValue *GV,
5925 CodeGen::CodeGenModule &M) const {
5926 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5927 if (!FD) return;
5928
5929 llvm::Function *F = cast<llvm::Function>(GV);
5930
David Blaikiebbafb8a2012-03-11 07:00:24 +00005931 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005932 if (FD->hasAttr<OpenCLKernelAttr>()) {
5933 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005934 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005935 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5936 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005937 // Convert the reqd_work_group_size() attributes to metadata.
5938 llvm::LLVMContext &Context = F->getContext();
5939 llvm::NamedMDNode *OpenCLMetadata =
5940 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5941
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005942 SmallVector<llvm::Metadata *, 5> Operands;
5943 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005944
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005945 Operands.push_back(
5946 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5947 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5948 Operands.push_back(
5949 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5950 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5951 Operands.push_back(
5952 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5953 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005954
5955 // Add a boolean constant operand for "required" (true) or "hint" (false)
5956 // for implementing the work_group_size_hint attr later. Currently
5957 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005958 Operands.push_back(
5959 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005960 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5961 }
5962 }
5963 }
5964}
5965
5966}
John McCall943fae92010-05-27 06:19:26 +00005967
Tony Linthicum76329bf2011-12-12 21:14:55 +00005968//===----------------------------------------------------------------------===//
5969// Hexagon ABI Implementation
5970//===----------------------------------------------------------------------===//
5971
5972namespace {
5973
5974class HexagonABIInfo : public ABIInfo {
5975
5976
5977public:
5978 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5979
5980private:
5981
5982 ABIArgInfo classifyReturnType(QualType RetTy) const;
5983 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5984
Craig Topper4f12f102014-03-12 06:41:41 +00005985 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005986
Craig Topper4f12f102014-03-12 06:41:41 +00005987 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5988 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005989};
5990
5991class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5992public:
5993 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5994 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5995
Craig Topper4f12f102014-03-12 06:41:41 +00005996 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005997 return 29;
5998 }
5999};
6000
6001}
6002
6003void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006004 if (!getCXXABI().classifyReturnType(FI))
6005 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006006 for (auto &I : FI.arguments())
6007 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006008}
6009
6010ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6011 if (!isAggregateTypeForABI(Ty)) {
6012 // Treat an enum type as its underlying type.
6013 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6014 Ty = EnumTy->getDecl()->getIntegerType();
6015
6016 return (Ty->isPromotableIntegerType() ?
6017 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6018 }
6019
6020 // Ignore empty records.
6021 if (isEmptyRecord(getContext(), Ty, true))
6022 return ABIArgInfo::getIgnore();
6023
Mark Lacey3825e832013-10-06 01:33:34 +00006024 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006025 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006026
6027 uint64_t Size = getContext().getTypeSize(Ty);
6028 if (Size > 64)
6029 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6030 // Pass in the smallest viable integer type.
6031 else if (Size > 32)
6032 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6033 else if (Size > 16)
6034 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6035 else if (Size > 8)
6036 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6037 else
6038 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6039}
6040
6041ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6042 if (RetTy->isVoidType())
6043 return ABIArgInfo::getIgnore();
6044
6045 // Large vector types should be returned via memory.
6046 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6047 return ABIArgInfo::getIndirect(0);
6048
6049 if (!isAggregateTypeForABI(RetTy)) {
6050 // Treat an enum type as its underlying type.
6051 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6052 RetTy = EnumTy->getDecl()->getIntegerType();
6053
6054 return (RetTy->isPromotableIntegerType() ?
6055 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6056 }
6057
Tony Linthicum76329bf2011-12-12 21:14:55 +00006058 if (isEmptyRecord(getContext(), RetTy, true))
6059 return ABIArgInfo::getIgnore();
6060
6061 // Aggregates <= 8 bytes are returned in r0; other aggregates
6062 // are returned indirectly.
6063 uint64_t Size = getContext().getTypeSize(RetTy);
6064 if (Size <= 64) {
6065 // Return in the smallest viable integer type.
6066 if (Size <= 8)
6067 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6068 if (Size <= 16)
6069 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6070 if (Size <= 32)
6071 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6072 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6073 }
6074
6075 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6076}
6077
6078llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006079 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006080 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006081 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006082
6083 CGBuilderTy &Builder = CGF.Builder;
6084 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6085 "ap");
6086 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6087 llvm::Type *PTy =
6088 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6089 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6090
6091 uint64_t Offset =
6092 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6093 llvm::Value *NextAddr =
6094 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6095 "ap.next");
6096 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6097
6098 return AddrTyped;
6099}
6100
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006101//===----------------------------------------------------------------------===//
6102// AMDGPU ABI Implementation
6103//===----------------------------------------------------------------------===//
6104
6105namespace {
6106
6107class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6108public:
6109 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6110 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6111 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6112 CodeGen::CodeGenModule &M) const override;
6113};
6114
6115}
6116
6117void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
6118 const Decl *D,
6119 llvm::GlobalValue *GV,
6120 CodeGen::CodeGenModule &M) const {
6121 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6122 if (!FD)
6123 return;
6124
6125 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6126 llvm::Function *F = cast<llvm::Function>(GV);
6127 uint32_t NumVGPR = Attr->getNumVGPR();
6128 if (NumVGPR != 0)
6129 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6130 }
6131
6132 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6133 llvm::Function *F = cast<llvm::Function>(GV);
6134 unsigned NumSGPR = Attr->getNumSGPR();
6135 if (NumSGPR != 0)
6136 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6137 }
6138}
6139
Tony Linthicum76329bf2011-12-12 21:14:55 +00006140
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006141//===----------------------------------------------------------------------===//
6142// SPARC v9 ABI Implementation.
6143// Based on the SPARC Compliance Definition version 2.4.1.
6144//
6145// Function arguments a mapped to a nominal "parameter array" and promoted to
6146// registers depending on their type. Each argument occupies 8 or 16 bytes in
6147// the array, structs larger than 16 bytes are passed indirectly.
6148//
6149// One case requires special care:
6150//
6151// struct mixed {
6152// int i;
6153// float f;
6154// };
6155//
6156// When a struct mixed is passed by value, it only occupies 8 bytes in the
6157// parameter array, but the int is passed in an integer register, and the float
6158// is passed in a floating point register. This is represented as two arguments
6159// with the LLVM IR inreg attribute:
6160//
6161// declare void f(i32 inreg %i, float inreg %f)
6162//
6163// The code generator will only allocate 4 bytes from the parameter array for
6164// the inreg arguments. All other arguments are allocated a multiple of 8
6165// bytes.
6166//
6167namespace {
6168class SparcV9ABIInfo : public ABIInfo {
6169public:
6170 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6171
6172private:
6173 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006174 void computeInfo(CGFunctionInfo &FI) const override;
6175 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6176 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006177
6178 // Coercion type builder for structs passed in registers. The coercion type
6179 // serves two purposes:
6180 //
6181 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6182 // in registers.
6183 // 2. Expose aligned floating point elements as first-level elements, so the
6184 // code generator knows to pass them in floating point registers.
6185 //
6186 // We also compute the InReg flag which indicates that the struct contains
6187 // aligned 32-bit floats.
6188 //
6189 struct CoerceBuilder {
6190 llvm::LLVMContext &Context;
6191 const llvm::DataLayout &DL;
6192 SmallVector<llvm::Type*, 8> Elems;
6193 uint64_t Size;
6194 bool InReg;
6195
6196 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6197 : Context(c), DL(dl), Size(0), InReg(false) {}
6198
6199 // Pad Elems with integers until Size is ToSize.
6200 void pad(uint64_t ToSize) {
6201 assert(ToSize >= Size && "Cannot remove elements");
6202 if (ToSize == Size)
6203 return;
6204
6205 // Finish the current 64-bit word.
6206 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6207 if (Aligned > Size && Aligned <= ToSize) {
6208 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6209 Size = Aligned;
6210 }
6211
6212 // Add whole 64-bit words.
6213 while (Size + 64 <= ToSize) {
6214 Elems.push_back(llvm::Type::getInt64Ty(Context));
6215 Size += 64;
6216 }
6217
6218 // Final in-word padding.
6219 if (Size < ToSize) {
6220 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6221 Size = ToSize;
6222 }
6223 }
6224
6225 // Add a floating point element at Offset.
6226 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6227 // Unaligned floats are treated as integers.
6228 if (Offset % Bits)
6229 return;
6230 // The InReg flag is only required if there are any floats < 64 bits.
6231 if (Bits < 64)
6232 InReg = true;
6233 pad(Offset);
6234 Elems.push_back(Ty);
6235 Size = Offset + Bits;
6236 }
6237
6238 // Add a struct type to the coercion type, starting at Offset (in bits).
6239 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6240 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6241 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6242 llvm::Type *ElemTy = StrTy->getElementType(i);
6243 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6244 switch (ElemTy->getTypeID()) {
6245 case llvm::Type::StructTyID:
6246 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6247 break;
6248 case llvm::Type::FloatTyID:
6249 addFloat(ElemOffset, ElemTy, 32);
6250 break;
6251 case llvm::Type::DoubleTyID:
6252 addFloat(ElemOffset, ElemTy, 64);
6253 break;
6254 case llvm::Type::FP128TyID:
6255 addFloat(ElemOffset, ElemTy, 128);
6256 break;
6257 case llvm::Type::PointerTyID:
6258 if (ElemOffset % 64 == 0) {
6259 pad(ElemOffset);
6260 Elems.push_back(ElemTy);
6261 Size += 64;
6262 }
6263 break;
6264 default:
6265 break;
6266 }
6267 }
6268 }
6269
6270 // Check if Ty is a usable substitute for the coercion type.
6271 bool isUsableType(llvm::StructType *Ty) const {
6272 if (Ty->getNumElements() != Elems.size())
6273 return false;
6274 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6275 if (Elems[i] != Ty->getElementType(i))
6276 return false;
6277 return true;
6278 }
6279
6280 // Get the coercion type as a literal struct type.
6281 llvm::Type *getType() const {
6282 if (Elems.size() == 1)
6283 return Elems.front();
6284 else
6285 return llvm::StructType::get(Context, Elems);
6286 }
6287 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006288};
6289} // end anonymous namespace
6290
6291ABIArgInfo
6292SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6293 if (Ty->isVoidType())
6294 return ABIArgInfo::getIgnore();
6295
6296 uint64_t Size = getContext().getTypeSize(Ty);
6297
6298 // Anything too big to fit in registers is passed with an explicit indirect
6299 // pointer / sret pointer.
6300 if (Size > SizeLimit)
6301 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6302
6303 // Treat an enum type as its underlying type.
6304 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6305 Ty = EnumTy->getDecl()->getIntegerType();
6306
6307 // Integer types smaller than a register are extended.
6308 if (Size < 64 && Ty->isIntegerType())
6309 return ABIArgInfo::getExtend();
6310
6311 // Other non-aggregates go in registers.
6312 if (!isAggregateTypeForABI(Ty))
6313 return ABIArgInfo::getDirect();
6314
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006315 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6316 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6317 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6318 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6319
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006320 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006321 // Build a coercion type from the LLVM struct type.
6322 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6323 if (!StrTy)
6324 return ABIArgInfo::getDirect();
6325
6326 CoerceBuilder CB(getVMContext(), getDataLayout());
6327 CB.addStruct(0, StrTy);
6328 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6329
6330 // Try to use the original type for coercion.
6331 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6332
6333 if (CB.InReg)
6334 return ABIArgInfo::getDirectInReg(CoerceTy);
6335 else
6336 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006337}
6338
6339llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6340 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006341 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6342 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6343 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6344 AI.setCoerceToType(ArgTy);
6345
6346 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6347 CGBuilderTy &Builder = CGF.Builder;
6348 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6349 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6350 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6351 llvm::Value *ArgAddr;
6352 unsigned Stride;
6353
6354 switch (AI.getKind()) {
6355 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006356 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006357 llvm_unreachable("Unsupported ABI kind for va_arg");
6358
6359 case ABIArgInfo::Extend:
6360 Stride = 8;
6361 ArgAddr = Builder
6362 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6363 "extend");
6364 break;
6365
6366 case ABIArgInfo::Direct:
6367 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6368 ArgAddr = Addr;
6369 break;
6370
6371 case ABIArgInfo::Indirect:
6372 Stride = 8;
6373 ArgAddr = Builder.CreateBitCast(Addr,
6374 llvm::PointerType::getUnqual(ArgPtrTy),
6375 "indirect");
6376 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6377 break;
6378
6379 case ABIArgInfo::Ignore:
6380 return llvm::UndefValue::get(ArgPtrTy);
6381 }
6382
6383 // Update VAList.
6384 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6385 Builder.CreateStore(Addr, VAListAddrAsBPP);
6386
6387 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006388}
6389
6390void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6391 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006392 for (auto &I : FI.arguments())
6393 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006394}
6395
6396namespace {
6397class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6398public:
6399 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6400 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006401
Craig Topper4f12f102014-03-12 06:41:41 +00006402 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006403 return 14;
6404 }
6405
6406 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006407 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006408};
6409} // end anonymous namespace
6410
Roman Divackyf02c9942014-02-24 18:46:27 +00006411bool
6412SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6413 llvm::Value *Address) const {
6414 // This is calculated from the LLVM and GCC tables and verified
6415 // against gcc output. AFAIK all ABIs use the same encoding.
6416
6417 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6418
6419 llvm::IntegerType *i8 = CGF.Int8Ty;
6420 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6421 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6422
6423 // 0-31: the 8-byte general-purpose registers
6424 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6425
6426 // 32-63: f0-31, the 4-byte floating-point registers
6427 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6428
6429 // Y = 64
6430 // PSR = 65
6431 // WIM = 66
6432 // TBR = 67
6433 // PC = 68
6434 // NPC = 69
6435 // FSR = 70
6436 // CSR = 71
6437 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6438
6439 // 72-87: d0-15, the 8-byte floating-point registers
6440 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6441
6442 return false;
6443}
6444
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006445
Robert Lytton0e076492013-08-13 09:43:10 +00006446//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006447// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006448//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006449
Robert Lytton0e076492013-08-13 09:43:10 +00006450namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006451
6452/// A SmallStringEnc instance is used to build up the TypeString by passing
6453/// it by reference between functions that append to it.
6454typedef llvm::SmallString<128> SmallStringEnc;
6455
6456/// TypeStringCache caches the meta encodings of Types.
6457///
6458/// The reason for caching TypeStrings is two fold:
6459/// 1. To cache a type's encoding for later uses;
6460/// 2. As a means to break recursive member type inclusion.
6461///
6462/// A cache Entry can have a Status of:
6463/// NonRecursive: The type encoding is not recursive;
6464/// Recursive: The type encoding is recursive;
6465/// Incomplete: An incomplete TypeString;
6466/// IncompleteUsed: An incomplete TypeString that has been used in a
6467/// Recursive type encoding.
6468///
6469/// A NonRecursive entry will have all of its sub-members expanded as fully
6470/// as possible. Whilst it may contain types which are recursive, the type
6471/// itself is not recursive and thus its encoding may be safely used whenever
6472/// the type is encountered.
6473///
6474/// A Recursive entry will have all of its sub-members expanded as fully as
6475/// possible. The type itself is recursive and it may contain other types which
6476/// are recursive. The Recursive encoding must not be used during the expansion
6477/// of a recursive type's recursive branch. For simplicity the code uses
6478/// IncompleteCount to reject all usage of Recursive encodings for member types.
6479///
6480/// An Incomplete entry is always a RecordType and only encodes its
6481/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6482/// are placed into the cache during type expansion as a means to identify and
6483/// handle recursive inclusion of types as sub-members. If there is recursion
6484/// the entry becomes IncompleteUsed.
6485///
6486/// During the expansion of a RecordType's members:
6487///
6488/// If the cache contains a NonRecursive encoding for the member type, the
6489/// cached encoding is used;
6490///
6491/// If the cache contains a Recursive encoding for the member type, the
6492/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6493///
6494/// If the member is a RecordType, an Incomplete encoding is placed into the
6495/// cache to break potential recursive inclusion of itself as a sub-member;
6496///
6497/// Once a member RecordType has been expanded, its temporary incomplete
6498/// entry is removed from the cache. If a Recursive encoding was swapped out
6499/// it is swapped back in;
6500///
6501/// If an incomplete entry is used to expand a sub-member, the incomplete
6502/// entry is marked as IncompleteUsed. The cache keeps count of how many
6503/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6504///
6505/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6506/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6507/// Else the member is part of a recursive type and thus the recursion has
6508/// been exited too soon for the encoding to be correct for the member.
6509///
6510class TypeStringCache {
6511 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6512 struct Entry {
6513 std::string Str; // The encoded TypeString for the type.
6514 enum Status State; // Information about the encoding in 'Str'.
6515 std::string Swapped; // A temporary place holder for a Recursive encoding
6516 // during the expansion of RecordType's members.
6517 };
6518 std::map<const IdentifierInfo *, struct Entry> Map;
6519 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6520 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6521public:
Robert Lyttond263f142014-05-06 09:38:54 +00006522 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006523 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6524 bool removeIncomplete(const IdentifierInfo *ID);
6525 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6526 bool IsRecursive);
6527 StringRef lookupStr(const IdentifierInfo *ID);
6528};
6529
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006530/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006531/// FieldEncoding is a helper for this ordering process.
6532class FieldEncoding {
6533 bool HasName;
6534 std::string Enc;
6535public:
6536 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6537 StringRef str() {return Enc.c_str();};
6538 bool operator<(const FieldEncoding &rhs) const {
6539 if (HasName != rhs.HasName) return HasName;
6540 return Enc < rhs.Enc;
6541 }
6542};
6543
Robert Lytton7d1db152013-08-19 09:46:39 +00006544class XCoreABIInfo : public DefaultABIInfo {
6545public:
6546 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006547 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6548 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006549};
6550
Robert Lyttond21e2d72014-03-03 13:45:29 +00006551class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006552 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006553public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006554 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006555 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006556 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6557 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006558};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006559
Robert Lytton2d196952013-10-11 10:29:34 +00006560} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006561
Robert Lytton7d1db152013-08-19 09:46:39 +00006562llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6563 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006564 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006565
Robert Lytton2d196952013-10-11 10:29:34 +00006566 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006567 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6568 CGF.Int8PtrPtrTy);
6569 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006570
Robert Lytton2d196952013-10-11 10:29:34 +00006571 // Handle the argument.
6572 ABIArgInfo AI = classifyArgumentType(Ty);
6573 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6574 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6575 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006576 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006577 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006578 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006579 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006580 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006581 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006582 llvm_unreachable("Unsupported ABI kind for va_arg");
6583 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006584 Val = llvm::UndefValue::get(ArgPtrTy);
6585 ArgSize = 0;
6586 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006587 case ABIArgInfo::Extend:
6588 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006589 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6590 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6591 if (ArgSize < 4)
6592 ArgSize = 4;
6593 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006594 case ABIArgInfo::Indirect:
6595 llvm::Value *ArgAddr;
6596 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6597 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006598 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6599 ArgSize = 4;
6600 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006601 }
Robert Lytton2d196952013-10-11 10:29:34 +00006602
6603 // Increment the VAList.
6604 if (ArgSize) {
6605 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6606 Builder.CreateStore(APN, VAListAddrAsBPP);
6607 }
6608 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006609}
Robert Lytton0e076492013-08-13 09:43:10 +00006610
Robert Lytton844aeeb2014-05-02 09:33:20 +00006611/// During the expansion of a RecordType, an incomplete TypeString is placed
6612/// into the cache as a means to identify and break recursion.
6613/// If there is a Recursive encoding in the cache, it is swapped out and will
6614/// be reinserted by removeIncomplete().
6615/// All other types of encoding should have been used rather than arriving here.
6616void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6617 std::string StubEnc) {
6618 if (!ID)
6619 return;
6620 Entry &E = Map[ID];
6621 assert( (E.Str.empty() || E.State == Recursive) &&
6622 "Incorrectly use of addIncomplete");
6623 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6624 E.Swapped.swap(E.Str); // swap out the Recursive
6625 E.Str.swap(StubEnc);
6626 E.State = Incomplete;
6627 ++IncompleteCount;
6628}
6629
6630/// Once the RecordType has been expanded, the temporary incomplete TypeString
6631/// must be removed from the cache.
6632/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6633/// Returns true if the RecordType was defined recursively.
6634bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6635 if (!ID)
6636 return false;
6637 auto I = Map.find(ID);
6638 assert(I != Map.end() && "Entry not present");
6639 Entry &E = I->second;
6640 assert( (E.State == Incomplete ||
6641 E.State == IncompleteUsed) &&
6642 "Entry must be an incomplete type");
6643 bool IsRecursive = false;
6644 if (E.State == IncompleteUsed) {
6645 // We made use of our Incomplete encoding, thus we are recursive.
6646 IsRecursive = true;
6647 --IncompleteUsedCount;
6648 }
6649 if (E.Swapped.empty())
6650 Map.erase(I);
6651 else {
6652 // Swap the Recursive back.
6653 E.Swapped.swap(E.Str);
6654 E.Swapped.clear();
6655 E.State = Recursive;
6656 }
6657 --IncompleteCount;
6658 return IsRecursive;
6659}
6660
6661/// Add the encoded TypeString to the cache only if it is NonRecursive or
6662/// Recursive (viz: all sub-members were expanded as fully as possible).
6663void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6664 bool IsRecursive) {
6665 if (!ID || IncompleteUsedCount)
6666 return; // No key or it is is an incomplete sub-type so don't add.
6667 Entry &E = Map[ID];
6668 if (IsRecursive && !E.Str.empty()) {
6669 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6670 "This is not the same Recursive entry");
6671 // The parent container was not recursive after all, so we could have used
6672 // this Recursive sub-member entry after all, but we assumed the worse when
6673 // we started viz: IncompleteCount!=0.
6674 return;
6675 }
6676 assert(E.Str.empty() && "Entry already present");
6677 E.Str = Str.str();
6678 E.State = IsRecursive? Recursive : NonRecursive;
6679}
6680
6681/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6682/// are recursively expanding a type (IncompleteCount != 0) and the cached
6683/// encoding is Recursive, return an empty StringRef.
6684StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6685 if (!ID)
6686 return StringRef(); // We have no key.
6687 auto I = Map.find(ID);
6688 if (I == Map.end())
6689 return StringRef(); // We have no encoding.
6690 Entry &E = I->second;
6691 if (E.State == Recursive && IncompleteCount)
6692 return StringRef(); // We don't use Recursive encodings for member types.
6693
6694 if (E.State == Incomplete) {
6695 // The incomplete type is being used to break out of recursion.
6696 E.State = IncompleteUsed;
6697 ++IncompleteUsedCount;
6698 }
6699 return E.Str.c_str();
6700}
6701
6702/// The XCore ABI includes a type information section that communicates symbol
6703/// type information to the linker. The linker uses this information to verify
6704/// safety/correctness of things such as array bound and pointers et al.
6705/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6706/// This type information (TypeString) is emitted into meta data for all global
6707/// symbols: definitions, declarations, functions & variables.
6708///
6709/// The TypeString carries type, qualifier, name, size & value details.
6710/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6711/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6712/// The output is tested by test/CodeGen/xcore-stringtype.c.
6713///
6714static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6715 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6716
6717/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6718void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6719 CodeGen::CodeGenModule &CGM) const {
6720 SmallStringEnc Enc;
6721 if (getTypeString(Enc, D, CGM, TSC)) {
6722 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006723 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6724 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006725 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6726 llvm::NamedMDNode *MD =
6727 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6728 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6729 }
6730}
6731
6732static bool appendType(SmallStringEnc &Enc, QualType QType,
6733 const CodeGen::CodeGenModule &CGM,
6734 TypeStringCache &TSC);
6735
6736/// Helper function for appendRecordType().
6737/// Builds a SmallVector containing the encoded field types in declaration order.
6738static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6739 const RecordDecl *RD,
6740 const CodeGen::CodeGenModule &CGM,
6741 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006742 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006743 SmallStringEnc Enc;
6744 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006745 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006746 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006747 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006748 Enc += "b(";
6749 llvm::raw_svector_ostream OS(Enc);
6750 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006751 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006752 OS.flush();
6753 Enc += ':';
6754 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006755 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006756 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006757 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006758 Enc += ')';
6759 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006760 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006761 }
6762 return true;
6763}
6764
6765/// Appends structure and union types to Enc and adds encoding to cache.
6766/// Recursively calls appendType (via extractFieldType) for each field.
6767/// Union types have their fields ordered according to the ABI.
6768static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6769 const CodeGen::CodeGenModule &CGM,
6770 TypeStringCache &TSC, const IdentifierInfo *ID) {
6771 // Append the cached TypeString if we have one.
6772 StringRef TypeString = TSC.lookupStr(ID);
6773 if (!TypeString.empty()) {
6774 Enc += TypeString;
6775 return true;
6776 }
6777
6778 // Start to emit an incomplete TypeString.
6779 size_t Start = Enc.size();
6780 Enc += (RT->isUnionType()? 'u' : 's');
6781 Enc += '(';
6782 if (ID)
6783 Enc += ID->getName();
6784 Enc += "){";
6785
6786 // We collect all encoded fields and order as necessary.
6787 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006788 const RecordDecl *RD = RT->getDecl()->getDefinition();
6789 if (RD && !RD->field_empty()) {
6790 // An incomplete TypeString stub is placed in the cache for this RecordType
6791 // so that recursive calls to this RecordType will use it whilst building a
6792 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006793 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006794 std::string StubEnc(Enc.substr(Start).str());
6795 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6796 TSC.addIncomplete(ID, std::move(StubEnc));
6797 if (!extractFieldType(FE, RD, CGM, TSC)) {
6798 (void) TSC.removeIncomplete(ID);
6799 return false;
6800 }
6801 IsRecursive = TSC.removeIncomplete(ID);
6802 // The ABI requires unions to be sorted but not structures.
6803 // See FieldEncoding::operator< for sort algorithm.
6804 if (RT->isUnionType())
6805 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006806 // We can now complete the TypeString.
6807 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006808 for (unsigned I = 0; I != E; ++I) {
6809 if (I)
6810 Enc += ',';
6811 Enc += FE[I].str();
6812 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006813 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006814 Enc += '}';
6815 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6816 return true;
6817}
6818
6819/// Appends enum types to Enc and adds the encoding to the cache.
6820static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6821 TypeStringCache &TSC,
6822 const IdentifierInfo *ID) {
6823 // Append the cached TypeString if we have one.
6824 StringRef TypeString = TSC.lookupStr(ID);
6825 if (!TypeString.empty()) {
6826 Enc += TypeString;
6827 return true;
6828 }
6829
6830 size_t Start = Enc.size();
6831 Enc += "e(";
6832 if (ID)
6833 Enc += ID->getName();
6834 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006835
6836 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006837 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006838 SmallVector<FieldEncoding, 16> FE;
6839 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6840 ++I) {
6841 SmallStringEnc EnumEnc;
6842 EnumEnc += "m(";
6843 EnumEnc += I->getName();
6844 EnumEnc += "){";
6845 I->getInitVal().toString(EnumEnc);
6846 EnumEnc += '}';
6847 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6848 }
6849 std::sort(FE.begin(), FE.end());
6850 unsigned E = FE.size();
6851 for (unsigned I = 0; I != E; ++I) {
6852 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006853 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006854 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006855 }
6856 }
6857 Enc += '}';
6858 TSC.addIfComplete(ID, Enc.substr(Start), false);
6859 return true;
6860}
6861
6862/// Appends type's qualifier to Enc.
6863/// This is done prior to appending the type's encoding.
6864static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6865 // Qualifiers are emitted in alphabetical order.
6866 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6867 int Lookup = 0;
6868 if (QT.isConstQualified())
6869 Lookup += 1<<0;
6870 if (QT.isRestrictQualified())
6871 Lookup += 1<<1;
6872 if (QT.isVolatileQualified())
6873 Lookup += 1<<2;
6874 Enc += Table[Lookup];
6875}
6876
6877/// Appends built-in types to Enc.
6878static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6879 const char *EncType;
6880 switch (BT->getKind()) {
6881 case BuiltinType::Void:
6882 EncType = "0";
6883 break;
6884 case BuiltinType::Bool:
6885 EncType = "b";
6886 break;
6887 case BuiltinType::Char_U:
6888 EncType = "uc";
6889 break;
6890 case BuiltinType::UChar:
6891 EncType = "uc";
6892 break;
6893 case BuiltinType::SChar:
6894 EncType = "sc";
6895 break;
6896 case BuiltinType::UShort:
6897 EncType = "us";
6898 break;
6899 case BuiltinType::Short:
6900 EncType = "ss";
6901 break;
6902 case BuiltinType::UInt:
6903 EncType = "ui";
6904 break;
6905 case BuiltinType::Int:
6906 EncType = "si";
6907 break;
6908 case BuiltinType::ULong:
6909 EncType = "ul";
6910 break;
6911 case BuiltinType::Long:
6912 EncType = "sl";
6913 break;
6914 case BuiltinType::ULongLong:
6915 EncType = "ull";
6916 break;
6917 case BuiltinType::LongLong:
6918 EncType = "sll";
6919 break;
6920 case BuiltinType::Float:
6921 EncType = "ft";
6922 break;
6923 case BuiltinType::Double:
6924 EncType = "d";
6925 break;
6926 case BuiltinType::LongDouble:
6927 EncType = "ld";
6928 break;
6929 default:
6930 return false;
6931 }
6932 Enc += EncType;
6933 return true;
6934}
6935
6936/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6937static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6938 const CodeGen::CodeGenModule &CGM,
6939 TypeStringCache &TSC) {
6940 Enc += "p(";
6941 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6942 return false;
6943 Enc += ')';
6944 return true;
6945}
6946
6947/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006948static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6949 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006950 const CodeGen::CodeGenModule &CGM,
6951 TypeStringCache &TSC, StringRef NoSizeEnc) {
6952 if (AT->getSizeModifier() != ArrayType::Normal)
6953 return false;
6954 Enc += "a(";
6955 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6956 CAT->getSize().toStringUnsigned(Enc);
6957 else
6958 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6959 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006960 // The Qualifiers should be attached to the type rather than the array.
6961 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006962 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6963 return false;
6964 Enc += ')';
6965 return true;
6966}
6967
6968/// Appends a function encoding to Enc, calling appendType for the return type
6969/// and the arguments.
6970static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6971 const CodeGen::CodeGenModule &CGM,
6972 TypeStringCache &TSC) {
6973 Enc += "f{";
6974 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6975 return false;
6976 Enc += "}(";
6977 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6978 // N.B. we are only interested in the adjusted param types.
6979 auto I = FPT->param_type_begin();
6980 auto E = FPT->param_type_end();
6981 if (I != E) {
6982 do {
6983 if (!appendType(Enc, *I, CGM, TSC))
6984 return false;
6985 ++I;
6986 if (I != E)
6987 Enc += ',';
6988 } while (I != E);
6989 if (FPT->isVariadic())
6990 Enc += ",va";
6991 } else {
6992 if (FPT->isVariadic())
6993 Enc += "va";
6994 else
6995 Enc += '0';
6996 }
6997 }
6998 Enc += ')';
6999 return true;
7000}
7001
7002/// Handles the type's qualifier before dispatching a call to handle specific
7003/// type encodings.
7004static bool appendType(SmallStringEnc &Enc, QualType QType,
7005 const CodeGen::CodeGenModule &CGM,
7006 TypeStringCache &TSC) {
7007
7008 QualType QT = QType.getCanonicalType();
7009
Robert Lytton6adb20f2014-06-05 09:06:21 +00007010 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7011 // The Qualifiers should be attached to the type rather than the array.
7012 // Thus we don't call appendQualifier() here.
7013 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7014
Robert Lytton844aeeb2014-05-02 09:33:20 +00007015 appendQualifier(Enc, QT);
7016
7017 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7018 return appendBuiltinType(Enc, BT);
7019
Robert Lytton844aeeb2014-05-02 09:33:20 +00007020 if (const PointerType *PT = QT->getAs<PointerType>())
7021 return appendPointerType(Enc, PT, CGM, TSC);
7022
7023 if (const EnumType *ET = QT->getAs<EnumType>())
7024 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7025
7026 if (const RecordType *RT = QT->getAsStructureType())
7027 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7028
7029 if (const RecordType *RT = QT->getAsUnionType())
7030 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7031
7032 if (const FunctionType *FT = QT->getAs<FunctionType>())
7033 return appendFunctionType(Enc, FT, CGM, TSC);
7034
7035 return false;
7036}
7037
7038static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7039 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7040 if (!D)
7041 return false;
7042
7043 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7044 if (FD->getLanguageLinkage() != CLanguageLinkage)
7045 return false;
7046 return appendType(Enc, FD->getType(), CGM, TSC);
7047 }
7048
7049 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7050 if (VD->getLanguageLinkage() != CLanguageLinkage)
7051 return false;
7052 QualType QT = VD->getType().getCanonicalType();
7053 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7054 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007055 // The Qualifiers should be attached to the type rather than the array.
7056 // Thus we don't call appendQualifier() here.
7057 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007058 }
7059 return appendType(Enc, QT, CGM, TSC);
7060 }
7061 return false;
7062}
7063
7064
Robert Lytton0e076492013-08-13 09:43:10 +00007065//===----------------------------------------------------------------------===//
7066// Driver code
7067//===----------------------------------------------------------------------===//
7068
Rafael Espindola9f834732014-09-19 01:54:22 +00007069const llvm::Triple &CodeGenModule::getTriple() const {
7070 return getTarget().getTriple();
7071}
7072
7073bool CodeGenModule::supportsCOMDAT() const {
7074 return !getTriple().isOSBinFormatMachO();
7075}
7076
Chris Lattner2b037972010-07-29 02:01:43 +00007077const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007078 if (TheTargetCodeGenInfo)
7079 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007080
John McCallc8e01702013-04-16 22:48:15 +00007081 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007082 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007083 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007084 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007085
Derek Schuff09338a22012-09-06 17:37:28 +00007086 case llvm::Triple::le32:
7087 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007088 case llvm::Triple::mips:
7089 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007090 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7091
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007092 case llvm::Triple::mips64:
7093 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007094 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7095
Tim Northover25e8a672014-05-24 12:51:25 +00007096 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007097 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007098 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007099 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007100 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007101
Tim Northover573cbee2014-05-24 12:52:07 +00007102 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007103 }
7104
Daniel Dunbard59655c2009-09-12 00:59:49 +00007105 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007106 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007107 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007108 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007109 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007110 if (Triple.getOS() == llvm::Triple::Win32) {
7111 TheTargetCodeGenInfo =
7112 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7113 return *TheTargetCodeGenInfo;
7114 }
7115
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007116 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007117 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007118 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007119 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007120 (CodeGenOpts.FloatABI != "soft" &&
7121 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007122 Kind = ARMABIInfo::AAPCS_VFP;
7123
Derek Schuff71658bd2015-01-29 00:47:04 +00007124 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007125 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007126
John McCallea8d8bb2010-03-11 00:10:12 +00007127 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007128 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007129 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007130 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007131 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007132 if (getTarget().getABI() == "elfv2")
7133 Kind = PPC64_SVR4_ABIInfo::ELFv2;
7134
Ulrich Weigandb7122372014-07-21 00:48:09 +00007135 return *(TheTargetCodeGenInfo =
7136 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7137 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007138 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007139 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007140 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007141 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007142 if (getTarget().getABI() == "elfv1")
7143 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7144
Ulrich Weigandb7122372014-07-21 00:48:09 +00007145 return *(TheTargetCodeGenInfo =
7146 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7147 }
John McCallea8d8bb2010-03-11 00:10:12 +00007148
Peter Collingbournec947aae2012-05-20 23:28:41 +00007149 case llvm::Triple::nvptx:
7150 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007151 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007152
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007153 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007154 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007155
Ulrich Weigand47445072013-05-06 16:26:41 +00007156 case llvm::Triple::systemz:
7157 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7158
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007159 case llvm::Triple::tce:
7160 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7161
Eli Friedman33465822011-07-08 23:31:17 +00007162 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007163 bool IsDarwinVectorABI = Triple.isOSDarwin();
7164 bool IsSmallStructInRegABI =
7165 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007166 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007167
John McCall1fe2a8c2013-06-18 02:46:29 +00007168 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007169 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007170 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007171 IsDarwinVectorABI, IsSmallStructInRegABI,
7172 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007173 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007174 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007175 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007176 new X86_32TargetCodeGenInfo(Types,
7177 IsDarwinVectorABI, IsSmallStructInRegABI,
7178 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007179 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007180 }
Eli Friedman33465822011-07-08 23:31:17 +00007181 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007182
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007183 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007184 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007185
Chris Lattner04dc9572010-08-31 16:44:54 +00007186 switch (Triple.getOS()) {
7187 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007188 return *(TheTargetCodeGenInfo =
7189 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007190 case llvm::Triple::PS4:
7191 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007192 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007193 return *(TheTargetCodeGenInfo =
7194 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007195 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007196 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007197 case llvm::Triple::hexagon:
7198 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007199 case llvm::Triple::r600:
7200 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007201 case llvm::Triple::amdgcn:
7202 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007203 case llvm::Triple::sparcv9:
7204 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007205 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007206 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007207 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007208}