blob: b6a53c9f45b28bae159dbbab68a9bc01b8ddfe2e [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) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000040 llvm::Value *Cell =
41 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall943fae92010-05-27 06:19:26 +000042 Builder.CreateStore(Value, Cell);
43 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
Anton Korobeynikov244360d2009-06-05 22:08:42 +000051ABIInfo::~ABIInfo() {}
52
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000053static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000054 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000055 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
56 if (!RD)
57 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000058 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000059}
60
61static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000062 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063 const RecordType *RT = T->getAs<RecordType>();
64 if (!RT)
65 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000066 return getRecordArgABI(RT, CXXABI);
67}
68
Reid Klecknerb1be6832014-11-15 01:41:41 +000069/// Pass transparent unions as if they were the type of the first element. Sema
70/// should ensure that all elements of the union have the same "machine type".
71static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
72 if (const RecordType *UT = Ty->getAsUnionType()) {
73 const RecordDecl *UD = UT->getDecl();
74 if (UD->hasAttr<TransparentUnionAttr>()) {
75 assert(!UD->field_empty() && "sema created an empty transparent union");
76 return UD->field_begin()->getType();
77 }
78 }
79 return Ty;
80}
81
Mark Lacey3825e832013-10-06 01:33:34 +000082CGCXXABI &ABIInfo::getCXXABI() const {
83 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000084}
85
Chris Lattner2b037972010-07-29 02:01:43 +000086ASTContext &ABIInfo::getContext() const {
87 return CGT.getContext();
88}
89
90llvm::LLVMContext &ABIInfo::getVMContext() const {
91 return CGT.getLLVMContext();
92}
93
Micah Villmowdd31ca12012-10-08 16:25:52 +000094const llvm::DataLayout &ABIInfo::getDataLayout() const {
95 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000096}
97
John McCallc8e01702013-04-16 22:48:15 +000098const TargetInfo &ABIInfo::getTarget() const {
99 return CGT.getTarget();
100}
Chris Lattner2b037972010-07-29 02:01:43 +0000101
Reid Klecknere9f6a712014-10-31 17:10:41 +0000102bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
103 return false;
104}
105
106bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
107 uint64_t Members) const {
108 return false;
109}
110
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000111void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000112 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000113 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 switch (TheKind) {
115 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000116 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000117 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000118 Ty->print(OS);
119 else
120 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000122 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000124 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000125 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000128 case InAlloca:
129 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
130 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000132 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000133 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000134 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000135 break;
136 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000137 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000138 break;
139 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000140 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000141}
142
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000143TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
144
John McCall3480ef22011-08-30 01:42:09 +0000145// If someone can figure out a general rule for this, that would be great.
146// It's probably just doomed to be platform-dependent, though.
147unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
148 // Verified for:
149 // x86-64 FreeBSD, Linux, Darwin
150 // x86-32 FreeBSD, Linux, Darwin
151 // PowerPC Linux, Darwin
152 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000153 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000154 return 32;
155}
156
John McCalla729c622012-02-17 03:33:10 +0000157bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
158 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000159 // The following conventions are known to require this to be false:
160 // x86_stdcall
161 // MIPS
162 // For everything else, we just prefer false unless we opt out.
163 return false;
164}
165
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000166void
167TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
168 llvm::SmallString<24> &Opt) const {
169 // This assumes the user is passing a library name like "rt" instead of a
170 // filename like "librt.a/so", and that they don't care whether it's static or
171 // dynamic.
172 Opt = "-l";
173 Opt += Lib;
174}
175
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000176static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000177
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000178/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000179/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000180static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
181 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000182 if (FD->isUnnamedBitfield())
183 return true;
184
185 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186
Eli Friedman0b3f2012011-11-18 03:47:20 +0000187 // Constant arrays of empty records count as empty, strip them off.
188 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000189 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000190 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
191 if (AT->getSize() == 0)
192 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000194 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000195
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000196 const RecordType *RT = FT->getAs<RecordType>();
197 if (!RT)
198 return false;
199
200 // C++ record fields are never empty, at least in the Itanium ABI.
201 //
202 // FIXME: We should use a predicate for whether this behavior is true in the
203 // current ABI.
204 if (isa<CXXRecordDecl>(RT->getDecl()))
205 return false;
206
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000207 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000208}
209
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000210/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211/// fields. Note that a structure with a flexible array member is not
212/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000213static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000214 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 if (!RT)
216 return 0;
217 const RecordDecl *RD = RT->getDecl();
218 if (RD->hasFlexibleArrayMember())
219 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000220
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000221 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000222 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000223 for (const auto &I : CXXRD->bases())
224 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000225 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000226
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000227 for (const auto *I : RD->fields())
228 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000229 return false;
230 return true;
231}
232
233/// isSingleElementStruct - Determine if a structure is a "single
234/// element struct", i.e. it has exactly one non-empty field or
235/// exactly one field which is itself a single element
236/// struct. Structures with flexible array members are never
237/// considered single element structs.
238///
239/// \return The field declaration for the single non-empty field, if
240/// it exists.
241static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000242 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000243 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000244 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000245
246 const RecordDecl *RD = RT->getDecl();
247 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000248 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249
Craig Topper8a13c412014-05-21 05:09:00 +0000250 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000251
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000252 // If this is a C++ record, check the bases first.
253 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000254 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000255 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000256 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000257 continue;
258
259 // If we already found an element then this isn't a single-element struct.
260 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000261 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000262
263 // If this is non-empty and not a single element struct, the composite
264 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000265 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000266 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000267 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000268 }
269 }
270
271 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000272 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000273 QualType FT = FD->getType();
274
275 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000276 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000277 continue;
278
279 // If we already found an element then this isn't a single-element
280 // struct.
281 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000282 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283
284 // Treat single element arrays as the element.
285 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
286 if (AT->getSize().getZExtValue() != 1)
287 break;
288 FT = AT->getElementType();
289 }
290
John McCalla1dee5302010-08-22 10:59:02 +0000291 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000292 Found = FT.getTypePtr();
293 } else {
294 Found = isSingleElementStruct(FT, Context);
295 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000296 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000297 }
298 }
299
Eli Friedmanee945342011-11-18 01:25:50 +0000300 // We don't consider a struct a single-element struct if it has
301 // padding beyond the element type.
302 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000303 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000304
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000305 return Found;
306}
307
308static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000309 // Treat complex types as the element type.
310 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
311 Ty = CTy->getElementType();
312
313 // Check for a type which we know has a simple scalar argument-passing
314 // convention without any padding. (We're specifically looking for 32
315 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000316 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000317 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000318 return false;
319
320 uint64_t Size = Context.getTypeSize(Ty);
321 return Size == 32 || Size == 64;
322}
323
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000324/// canExpandIndirectArgument - Test whether an argument type which is to be
325/// passed indirectly (on the stack) would have the equivalent layout if it was
326/// expanded into separate arguments. If so, we prefer to do the latter to avoid
327/// inhibiting optimizations.
328///
329// FIXME: This predicate is missing many cases, currently it just follows
330// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
331// should probably make this smarter, or better yet make the LLVM backend
332// capable of handling it.
333static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
334 // We can only expand structure types.
335 const RecordType *RT = Ty->getAs<RecordType>();
336 if (!RT)
337 return false;
338
339 // We can only expand (C) structures.
340 //
341 // FIXME: This needs to be generalized to handle classes as well.
342 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000343 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000344 return false;
345
Manman Ren27382782015-04-03 18:10:29 +0000346 // We try to expand CLike CXXRecordDecl.
347 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
348 if (!CXXRD->isCLike())
349 return false;
350 }
351
Eli Friedmane5c85622011-11-18 01:32:26 +0000352 uint64_t Size = 0;
353
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000354 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000355 if (!is32Or64BitBasicType(FD->getType(), Context))
356 return false;
357
358 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
359 // how to expand them yet, and the predicate for telling if a bitfield still
360 // counts as "basic" is more complicated than what we were doing previously.
361 if (FD->isBitField())
362 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000363
364 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365 }
366
Eli Friedmane5c85622011-11-18 01:32:26 +0000367 // Make sure there are not any holes in the struct.
368 if (Size != Context.getTypeSize(Ty))
369 return false;
370
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000371 return true;
372}
373
374namespace {
375/// DefaultABIInfo - The default implementation for ABI specific
376/// details. This implementation provides information which results in
377/// self-consistent and sensible LLVM IR generation, but does not
378/// conform to any particular ABI.
379class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000380public:
381 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000382
Chris Lattner458b2aa2010-07-29 02:16:43 +0000383 ABIArgInfo classifyReturnType(QualType RetTy) const;
384 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000385
Craig Topper4f12f102014-03-12 06:41:41 +0000386 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000387 if (!getCXXABI().classifyReturnType(FI))
388 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000389 for (auto &I : FI.arguments())
390 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000391 }
392
Craig Topper4f12f102014-03-12 06:41:41 +0000393 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
394 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000395};
396
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000397class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
398public:
Chris Lattner2b037972010-07-29 02:01:43 +0000399 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
400 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000401};
402
403llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
404 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000405 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000406}
407
Chris Lattner458b2aa2010-07-29 02:16:43 +0000408ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000409 Ty = useFirstFieldIfTransparentUnion(Ty);
410
411 if (isAggregateTypeForABI(Ty)) {
412 // Records with non-trivial destructors/copy-constructors should not be
413 // passed by value.
414 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
415 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
416
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000417 return ABIArgInfo::getIndirect(0);
Reid Klecknerac385062015-05-18 22:46:30 +0000418 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000419
Chris Lattner9723d6c2010-03-11 18:19:55 +0000420 // Treat an enum type as its underlying type.
421 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
422 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000423
Chris Lattner9723d6c2010-03-11 18:19:55 +0000424 return (Ty->isPromotableIntegerType() ?
425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000426}
427
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000428ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
429 if (RetTy->isVoidType())
430 return ABIArgInfo::getIgnore();
431
432 if (isAggregateTypeForABI(RetTy))
433 return ABIArgInfo::getIndirect(0);
434
435 // Treat an enum type as its underlying type.
436 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
437 RetTy = EnumTy->getDecl()->getIntegerType();
438
439 return (RetTy->isPromotableIntegerType() ?
440 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
441}
442
Derek Schuff09338a22012-09-06 17:37:28 +0000443//===----------------------------------------------------------------------===//
444// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000445//
446// This is a simplified version of the x86_32 ABI. Arguments and return values
447// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000448//===----------------------------------------------------------------------===//
449
450class PNaClABIInfo : public ABIInfo {
451 public:
452 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
453
454 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000455 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000456
Craig Topper4f12f102014-03-12 06:41:41 +0000457 void computeInfo(CGFunctionInfo &FI) const override;
458 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
459 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000460};
461
462class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
463 public:
464 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
465 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
466};
467
468void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000469 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000470 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
471
Reid Kleckner40ca9132014-05-13 22:05:45 +0000472 for (auto &I : FI.arguments())
473 I.info = classifyArgumentType(I.type);
474}
Derek Schuff09338a22012-09-06 17:37:28 +0000475
476llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
477 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000478 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000479}
480
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000481/// \brief Classify argument of given type \p Ty.
482ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000483 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000484 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000485 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000486 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000487 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
488 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000489 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000490 } else if (Ty->isFloatingType()) {
491 // Floating-point types don't go inreg.
492 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000493 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000494
495 return (Ty->isPromotableIntegerType() ?
496 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000497}
498
499ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
500 if (RetTy->isVoidType())
501 return ABIArgInfo::getIgnore();
502
Eli Benderskye20dad62013-04-04 22:49:35 +0000503 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000504 if (isAggregateTypeForABI(RetTy))
505 return ABIArgInfo::getIndirect(0);
506
507 // Treat an enum type as its underlying type.
508 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
509 RetTy = EnumTy->getDecl()->getIntegerType();
510
511 return (RetTy->isPromotableIntegerType() ?
512 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
513}
514
Chad Rosier651c1832013-03-25 21:00:27 +0000515/// IsX86_MMXType - Return true if this is an MMX type.
516bool IsX86_MMXType(llvm::Type *IRType) {
517 // 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 +0000518 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
519 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
520 IRType->getScalarSizeInBits() != 64;
521}
522
Jay Foad7c57be32011-07-11 09:56:20 +0000523static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000524 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000525 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000526 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
527 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
528 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000529 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000530 }
531
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000532 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000533 }
534
535 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000536 return Ty;
537}
538
Reid Kleckner80944df2014-10-31 22:00:51 +0000539/// Returns true if this type can be passed in SSE registers with the
540/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
541static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
542 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
543 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
544 return true;
545 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
546 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
547 // registers specially.
548 unsigned VecSize = Context.getTypeSize(VT);
549 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
550 return true;
551 }
552 return false;
553}
554
555/// Returns true if this aggregate is small enough to be passed in SSE registers
556/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
557static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
558 return NumMembers <= 4;
559}
560
Chris Lattner0cf24192010-06-28 20:05:43 +0000561//===----------------------------------------------------------------------===//
562// X86-32 ABI Implementation
563//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000564
Reid Kleckner661f35b2014-01-18 01:12:41 +0000565/// \brief Similar to llvm::CCState, but for Clang.
566struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000567 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000568
569 unsigned CC;
570 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000571 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000572};
573
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000574/// X86_32ABIInfo - The X86-32 ABI information.
575class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000576 enum Class {
577 Integer,
578 Float
579 };
580
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000581 static const unsigned MinABIStackAlignInBytes = 4;
582
David Chisnallde3a0692009-08-17 23:08:21 +0000583 bool IsDarwinVectorABI;
584 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000585 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000586 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587
588 static bool isRegisterSize(unsigned Size) {
589 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
590 }
591
Reid Kleckner80944df2014-10-31 22:00:51 +0000592 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
593 // FIXME: Assumes vectorcall is in use.
594 return isX86VectorTypeForVectorCall(getContext(), Ty);
595 }
596
597 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
598 uint64_t NumMembers) const override {
599 // FIXME: Assumes vectorcall is in use.
600 return isX86VectorCallAggregateSmallEnough(NumMembers);
601 }
602
Reid Kleckner40ca9132014-05-13 22:05:45 +0000603 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000604
Daniel Dunbar557893d2010-04-21 19:10:51 +0000605 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
606 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000607 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
608
609 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000610
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000611 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000612 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000613
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000614 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000615 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000616 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
617 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000618
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000619 /// \brief Rewrite the function info so that all memory arguments use
620 /// inalloca.
621 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
622
623 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
624 unsigned &StackOffset, ABIArgInfo &Info,
625 QualType Type) const;
626
Rafael Espindola75419dc2012-07-23 23:30:29 +0000627public:
628
Craig Topper4f12f102014-03-12 06:41:41 +0000629 void computeInfo(CGFunctionInfo &FI) const override;
630 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
631 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000632
Chad Rosier651c1832013-03-25 21:00:27 +0000633 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000634 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000635 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000636 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000637};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000638
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000639class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
640public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000641 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000642 bool d, bool p, bool w, unsigned r)
643 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000644
John McCall1fe2a8c2013-06-18 02:46:29 +0000645 static bool isStructReturnInRegABI(
646 const llvm::Triple &Triple, const CodeGenOptions &Opts);
647
Charles Davis4ea31ab2010-02-13 15:54:06 +0000648 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000649 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000650
Craig Topper4f12f102014-03-12 06:41:41 +0000651 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000652 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000653 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000654 return 4;
655 }
656
657 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000658 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000659
Jay Foad7c57be32011-07-11 09:56:20 +0000660 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000661 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000662 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000663 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
664 }
665
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000666 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
667 std::string &Constraints,
668 std::vector<llvm::Type *> &ResultRegTypes,
669 std::vector<llvm::Type *> &ResultTruncRegTypes,
670 std::vector<LValue> &ResultRegDests,
671 std::string &AsmString,
672 unsigned NumOutputs) const override;
673
Craig Topper4f12f102014-03-12 06:41:41 +0000674 llvm::Constant *
675 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000676 unsigned Sig = (0xeb << 0) | // jmp rel8
677 (0x06 << 8) | // .+0x08
678 ('F' << 16) |
679 ('T' << 24);
680 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
681 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000682};
683
684}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000685
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000686/// Rewrite input constraint references after adding some output constraints.
687/// In the case where there is one output and one input and we add one output,
688/// we need to replace all operand references greater than or equal to 1:
689/// mov $0, $1
690/// mov eax, $1
691/// The result will be:
692/// mov $0, $2
693/// mov eax, $2
694static void rewriteInputConstraintReferences(unsigned FirstIn,
695 unsigned NumNewOuts,
696 std::string &AsmString) {
697 std::string Buf;
698 llvm::raw_string_ostream OS(Buf);
699 size_t Pos = 0;
700 while (Pos < AsmString.size()) {
701 size_t DollarStart = AsmString.find('$', Pos);
702 if (DollarStart == std::string::npos)
703 DollarStart = AsmString.size();
704 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
705 if (DollarEnd == std::string::npos)
706 DollarEnd = AsmString.size();
707 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
708 Pos = DollarEnd;
709 size_t NumDollars = DollarEnd - DollarStart;
710 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
711 // We have an operand reference.
712 size_t DigitStart = Pos;
713 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
714 if (DigitEnd == std::string::npos)
715 DigitEnd = AsmString.size();
716 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
717 unsigned OperandIndex;
718 if (!OperandStr.getAsInteger(10, OperandIndex)) {
719 if (OperandIndex >= FirstIn)
720 OperandIndex += NumNewOuts;
721 OS << OperandIndex;
722 } else {
723 OS << OperandStr;
724 }
725 Pos = DigitEnd;
726 }
727 }
728 AsmString = std::move(OS.str());
729}
730
731/// Add output constraints for EAX:EDX because they are return registers.
732void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
733 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
734 std::vector<llvm::Type *> &ResultRegTypes,
735 std::vector<llvm::Type *> &ResultTruncRegTypes,
736 std::vector<LValue> &ResultRegDests, std::string &AsmString,
737 unsigned NumOutputs) const {
738 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
739
740 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
741 // larger.
742 if (!Constraints.empty())
743 Constraints += ',';
744 if (RetWidth <= 32) {
745 Constraints += "={eax}";
746 ResultRegTypes.push_back(CGF.Int32Ty);
747 } else {
748 // Use the 'A' constraint for EAX:EDX.
749 Constraints += "=A";
750 ResultRegTypes.push_back(CGF.Int64Ty);
751 }
752
753 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
754 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
755 ResultTruncRegTypes.push_back(CoerceTy);
756
757 // Coerce the integer by bitcasting the return slot pointer.
758 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
759 CoerceTy->getPointerTo()));
760 ResultRegDests.push_back(ReturnSlot);
761
762 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
763}
764
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000765/// shouldReturnTypeInRegister - Determine if the given type should be
766/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000767bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
768 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000769 uint64_t Size = Context.getTypeSize(Ty);
770
771 // Type must be register sized.
772 if (!isRegisterSize(Size))
773 return false;
774
775 if (Ty->isVectorType()) {
776 // 64- and 128- bit vectors inside structures are not returned in
777 // registers.
778 if (Size == 64 || Size == 128)
779 return false;
780
781 return true;
782 }
783
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000784 // If this is a builtin, pointer, enum, complex type, member pointer, or
785 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000786 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000787 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000788 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000789 return true;
790
791 // Arrays are treated like records.
792 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000793 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000794
795 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000796 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000797 if (!RT) return false;
798
Anders Carlsson40446e82010-01-27 03:25:19 +0000799 // FIXME: Traverse bases here too.
800
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801 // Structure types are passed in register if all fields would be
802 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000803 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000804 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000805 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000806 continue;
807
808 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000809 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000810 return false;
811 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000812 return true;
813}
814
Reid Kleckner661f35b2014-01-18 01:12:41 +0000815ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
816 // If the return value is indirect, then the hidden argument is consuming one
817 // integer register.
818 if (State.FreeRegs) {
819 --State.FreeRegs;
820 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
821 }
822 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
823}
824
Reid Kleckner40ca9132014-05-13 22:05:45 +0000825ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000826 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000827 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000828
Reid Kleckner80944df2014-10-31 22:00:51 +0000829 const Type *Base = nullptr;
830 uint64_t NumElts = 0;
831 if (State.CC == llvm::CallingConv::X86_VectorCall &&
832 isHomogeneousAggregate(RetTy, Base, NumElts)) {
833 // The LLVM struct type for such an aggregate should lower properly.
834 return ABIArgInfo::getDirect();
835 }
836
Chris Lattner458b2aa2010-07-29 02:16:43 +0000837 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000838 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000839 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000840 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000841
842 // 128-bit vectors are a special case; they are returned in
843 // registers and we need to make sure to pick a type the LLVM
844 // backend will like.
845 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000846 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000847 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000848
849 // Always return in register if it fits in a general purpose
850 // register, or if it is 64 bits and has a single element.
851 if ((Size == 8 || Size == 16 || Size == 32) ||
852 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000853 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000854 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000855
Reid Kleckner661f35b2014-01-18 01:12:41 +0000856 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000857 }
858
859 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000860 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000861
John McCalla1dee5302010-08-22 10:59:02 +0000862 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000863 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000864 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000865 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000866 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000867 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000868
David Chisnallde3a0692009-08-17 23:08:21 +0000869 // If specified, structs and unions are always indirect.
870 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000872
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000873 // Small structures which are register sized are generally returned
874 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000875 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000876 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000877
878 // As a special-case, if the struct is a "single-element" struct, and
879 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000880 // floating-point register. (MSVC does not apply this special case.)
881 // We apply a similar transformation for pointer types to improve the
882 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000883 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000884 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000885 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000886 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
887
888 // FIXME: We should be able to narrow this integer in cases with dead
889 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000890 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000891 }
892
Reid Kleckner661f35b2014-01-18 01:12:41 +0000893 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000894 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000895
Chris Lattner458b2aa2010-07-29 02:16:43 +0000896 // Treat an enum type as its underlying type.
897 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
898 RetTy = EnumTy->getDecl()->getIntegerType();
899
900 return (RetTy->isPromotableIntegerType() ?
901 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000902}
903
Eli Friedman7919bea2012-06-05 19:40:46 +0000904static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
905 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
906}
907
Daniel Dunbared23de32010-09-16 20:42:00 +0000908static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
909 const RecordType *RT = Ty->getAs<RecordType>();
910 if (!RT)
911 return 0;
912 const RecordDecl *RD = RT->getDecl();
913
914 // If this is a C++ record, check the bases first.
915 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000916 for (const auto &I : CXXRD->bases())
917 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000918 return false;
919
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000920 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000921 QualType FT = i->getType();
922
Eli Friedman7919bea2012-06-05 19:40:46 +0000923 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000924 return true;
925
926 if (isRecordWithSSEVectorType(Context, FT))
927 return true;
928 }
929
930 return false;
931}
932
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000933unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
934 unsigned Align) const {
935 // Otherwise, if the alignment is less than or equal to the minimum ABI
936 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000937 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000938 return 0; // Use default alignment.
939
940 // On non-Darwin, the stack type alignment is always 4.
941 if (!IsDarwinVectorABI) {
942 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000943 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000944 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000945
Daniel Dunbared23de32010-09-16 20:42:00 +0000946 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000947 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
948 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000949 return 16;
950
951 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000952}
953
Rafael Espindola703c47f2012-10-19 05:04:37 +0000954ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000955 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000956 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000957 if (State.FreeRegs) {
958 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000959 return ABIArgInfo::getIndirectInReg(0, false);
960 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000961 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000962 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000963
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000964 // Compute the byval alignment.
965 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
966 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
967 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000968 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000969
970 // If the stack alignment is less than the type alignment, realign the
971 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000972 bool Realign = TypeAlign > StackAlign;
973 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000974}
975
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000976X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
977 const Type *T = isSingleElementStruct(Ty, getContext());
978 if (!T)
979 T = Ty.getTypePtr();
980
981 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
982 BuiltinType::Kind K = BT->getKind();
983 if (K == BuiltinType::Float || K == BuiltinType::Double)
984 return Float;
985 }
986 return Integer;
987}
988
Reid Kleckner661f35b2014-01-18 01:12:41 +0000989bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
990 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000991 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000992 Class C = classify(Ty);
993 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000994 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000995
Rafael Espindola077dd592012-10-24 01:58:58 +0000996 unsigned Size = getContext().getTypeSize(Ty);
997 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000998
999 if (SizeInRegs == 0)
1000 return false;
1001
Reid Kleckner661f35b2014-01-18 01:12:41 +00001002 if (SizeInRegs > State.FreeRegs) {
1003 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001004 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001005 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001006
Reid Kleckner661f35b2014-01-18 01:12:41 +00001007 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001008
Reid Kleckner80944df2014-10-31 22:00:51 +00001009 if (State.CC == llvm::CallingConv::X86_FastCall ||
1010 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001011 if (Size > 32)
1012 return false;
1013
1014 if (Ty->isIntegralOrEnumerationType())
1015 return true;
1016
1017 if (Ty->isPointerType())
1018 return true;
1019
1020 if (Ty->isReferenceType())
1021 return true;
1022
Reid Kleckner661f35b2014-01-18 01:12:41 +00001023 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001024 NeedsPadding = true;
1025
Rafael Espindola077dd592012-10-24 01:58:58 +00001026 return false;
1027 }
1028
Rafael Espindola703c47f2012-10-19 05:04:37 +00001029 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001030}
1031
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001032ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1033 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001034 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001035
Reid Klecknerb1be6832014-11-15 01:41:41 +00001036 Ty = useFirstFieldIfTransparentUnion(Ty);
1037
Reid Kleckner80944df2014-10-31 22:00:51 +00001038 // Check with the C++ ABI first.
1039 const RecordType *RT = Ty->getAs<RecordType>();
1040 if (RT) {
1041 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1042 if (RAA == CGCXXABI::RAA_Indirect) {
1043 return getIndirectResult(Ty, false, State);
1044 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1045 // The field index doesn't matter, we'll fix it up later.
1046 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1047 }
1048 }
1049
1050 // vectorcall adds the concept of a homogenous vector aggregate, similar
1051 // to other targets.
1052 const Type *Base = nullptr;
1053 uint64_t NumElts = 0;
1054 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1055 isHomogeneousAggregate(Ty, Base, NumElts)) {
1056 if (State.FreeSSERegs >= NumElts) {
1057 State.FreeSSERegs -= NumElts;
1058 if (Ty->isBuiltinType() || Ty->isVectorType())
1059 return ABIArgInfo::getDirect();
1060 return ABIArgInfo::getExpand();
1061 }
1062 return getIndirectResult(Ty, /*ByVal=*/false, State);
1063 }
1064
1065 if (isAggregateTypeForABI(Ty)) {
1066 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001067 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001068 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001069 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001070
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001071 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001072 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001073 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001074 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001075
Eli Friedman9f061a32011-11-18 00:28:11 +00001076 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001077 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001078 return ABIArgInfo::getIgnore();
1079
Rafael Espindolafad28de2012-10-24 01:59:00 +00001080 llvm::LLVMContext &LLVMContext = getVMContext();
1081 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1082 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001083 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001084 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001085 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001086 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1087 return ABIArgInfo::getDirectInReg(Result);
1088 }
Craig Topper8a13c412014-05-21 05:09:00 +00001089 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001090
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001091 // Expand small (<= 128-bit) record types when we know that the stack layout
1092 // of those arguments will match the struct. This is important because the
1093 // LLVM backend isn't smart enough to remove byval, which inhibits many
1094 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001095 if (getContext().getTypeSize(Ty) <= 4*32 &&
1096 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001097 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001098 State.CC == llvm::CallingConv::X86_FastCall ||
1099 State.CC == llvm::CallingConv::X86_VectorCall,
1100 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101
Reid Kleckner661f35b2014-01-18 01:12:41 +00001102 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001103 }
1104
Chris Lattnerd774ae92010-08-26 20:05:13 +00001105 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001106 // On Darwin, some vectors are passed in memory, we handle this by passing
1107 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001108 if (IsDarwinVectorABI) {
1109 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001110 if ((Size == 8 || Size == 16 || Size == 32) ||
1111 (Size == 64 && VT->getNumElements() == 1))
1112 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1113 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001114 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001115
Chad Rosier651c1832013-03-25 21:00:27 +00001116 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1117 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001118
Chris Lattnerd774ae92010-08-26 20:05:13 +00001119 return ABIArgInfo::getDirect();
1120 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001121
1122
Chris Lattner458b2aa2010-07-29 02:16:43 +00001123 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1124 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001125
Rafael Espindolafad28de2012-10-24 01:59:00 +00001126 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001127 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001128
1129 if (Ty->isPromotableIntegerType()) {
1130 if (InReg)
1131 return ABIArgInfo::getExtendInReg();
1132 return ABIArgInfo::getExtend();
1133 }
1134 if (InReg)
1135 return ABIArgInfo::getDirectInReg();
1136 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001137}
1138
Rafael Espindolaa6472962012-07-24 00:01:07 +00001139void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001140 CCState State(FI.getCallingConvention());
1141 if (State.CC == llvm::CallingConv::X86_FastCall)
1142 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001143 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1144 State.FreeRegs = 2;
1145 State.FreeSSERegs = 6;
1146 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001147 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001148 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001149 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001150
Reid Kleckner677539d2014-07-10 01:58:55 +00001151 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001152 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001153 } else if (FI.getReturnInfo().isIndirect()) {
1154 // The C++ ABI is not aware of register usage, so we have to check if the
1155 // return value was sret and put it in a register ourselves if appropriate.
1156 if (State.FreeRegs) {
1157 --State.FreeRegs; // The sret parameter consumes a register.
1158 FI.getReturnInfo().setInReg(true);
1159 }
1160 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001161
Peter Collingbournef7706832014-12-12 23:41:25 +00001162 // The chain argument effectively gives us another free register.
1163 if (FI.isChainCall())
1164 ++State.FreeRegs;
1165
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001166 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001167 for (auto &I : FI.arguments()) {
1168 I.info = classifyArgumentType(I.type, State);
1169 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001170 }
1171
1172 // If we needed to use inalloca for any argument, do a second pass and rewrite
1173 // all the memory arguments to use inalloca.
1174 if (UsedInAlloca)
1175 rewriteWithInAlloca(FI);
1176}
1177
1178void
1179X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1180 unsigned &StackOffset,
1181 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001182 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1183 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1184 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1185 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1186
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001187 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1188 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001189 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001190 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001191 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001192 unsigned NumBytes = StackOffset - OldOffset;
1193 assert(NumBytes);
1194 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1195 Ty = llvm::ArrayType::get(Ty, NumBytes);
1196 FrameFields.push_back(Ty);
1197 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001198}
1199
Reid Kleckner852361d2014-07-26 00:12:26 +00001200static bool isArgInAlloca(const ABIArgInfo &Info) {
1201 // Leave ignored and inreg arguments alone.
1202 switch (Info.getKind()) {
1203 case ABIArgInfo::InAlloca:
1204 return true;
1205 case ABIArgInfo::Indirect:
1206 assert(Info.getIndirectByVal());
1207 return true;
1208 case ABIArgInfo::Ignore:
1209 return false;
1210 case ABIArgInfo::Direct:
1211 case ABIArgInfo::Extend:
1212 case ABIArgInfo::Expand:
1213 if (Info.getInReg())
1214 return false;
1215 return true;
1216 }
1217 llvm_unreachable("invalid enum");
1218}
1219
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001220void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1221 assert(IsWin32StructABI && "inalloca only supported on win32");
1222
1223 // Build a packed struct type for all of the arguments in memory.
1224 SmallVector<llvm::Type *, 6> FrameFields;
1225
1226 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001227 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1228
1229 // Put 'this' into the struct before 'sret', if necessary.
1230 bool IsThisCall =
1231 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1232 ABIArgInfo &Ret = FI.getReturnInfo();
1233 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1234 isArgInAlloca(I->info)) {
1235 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1236 ++I;
1237 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001238
1239 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001240 if (Ret.isIndirect() && !Ret.getInReg()) {
1241 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1242 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001243 // On Windows, the hidden sret parameter is always returned in eax.
1244 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001245 }
1246
1247 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001248 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001249 ++I;
1250
1251 // Put arguments passed in memory into the struct.
1252 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001253 if (isArgInAlloca(I->info))
1254 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001255 }
1256
1257 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1258 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001259}
1260
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001261llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1262 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001263 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001264
1265 CGBuilderTy &Builder = CGF.Builder;
1266 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1267 "ap");
1268 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001269
1270 // Compute if the address needs to be aligned
1271 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1272 Align = getTypeStackAlignInBytes(Ty, Align);
1273 Align = std::max(Align, 4U);
1274 if (Align > 4) {
1275 // addr = (addr + align - 1) & -align;
1276 llvm::Value *Offset =
1277 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1278 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1279 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1280 CGF.Int32Ty);
1281 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1282 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1283 Addr->getType(),
1284 "ap.cur.aligned");
1285 }
1286
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001287 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001288 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001289 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1290
1291 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001292 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001293 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001294 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001295 "ap.next");
1296 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1297
1298 return AddrTyped;
1299}
1300
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001301bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1302 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1303 assert(Triple.getArch() == llvm::Triple::x86);
1304
1305 switch (Opts.getStructReturnConvention()) {
1306 case CodeGenOptions::SRCK_Default:
1307 break;
1308 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1309 return false;
1310 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1311 return true;
1312 }
1313
1314 if (Triple.isOSDarwin())
1315 return true;
1316
1317 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001318 case llvm::Triple::DragonFly:
1319 case llvm::Triple::FreeBSD:
1320 case llvm::Triple::OpenBSD:
1321 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001322 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001323 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001324 default:
1325 return false;
1326 }
1327}
1328
Charles Davis4ea31ab2010-02-13 15:54:06 +00001329void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1330 llvm::GlobalValue *GV,
1331 CodeGen::CodeGenModule &CGM) const {
1332 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1333 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1334 // Get the LLVM function.
1335 llvm::Function *Fn = cast<llvm::Function>(GV);
1336
1337 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001338 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001339 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001340 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1341 llvm::AttributeSet::get(CGM.getLLVMContext(),
1342 llvm::AttributeSet::FunctionIndex,
1343 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001344 }
1345 }
1346}
1347
John McCallbeec5a02010-03-06 00:35:14 +00001348bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1349 CodeGen::CodeGenFunction &CGF,
1350 llvm::Value *Address) const {
1351 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001352
Chris Lattnerece04092012-02-07 00:39:47 +00001353 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001354
John McCallbeec5a02010-03-06 00:35:14 +00001355 // 0-7 are the eight integer registers; the order is different
1356 // on Darwin (for EH), but the range is the same.
1357 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001358 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001359
John McCallc8e01702013-04-16 22:48:15 +00001360 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001361 // 12-16 are st(0..4). Not sure why we stop at 4.
1362 // These have size 16, which is sizeof(long double) on
1363 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001364 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001365 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001366
John McCallbeec5a02010-03-06 00:35:14 +00001367 } else {
1368 // 9 is %eflags, which doesn't get a size on Darwin for some
1369 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001370 Builder.CreateStore(
1371 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001372
1373 // 11-16 are st(0..5). Not sure why we stop at 5.
1374 // These have size 12, which is sizeof(long double) on
1375 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001376 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001377 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1378 }
John McCallbeec5a02010-03-06 00:35:14 +00001379
1380 return false;
1381}
1382
Chris Lattner0cf24192010-06-28 20:05:43 +00001383//===----------------------------------------------------------------------===//
1384// X86-64 ABI Implementation
1385//===----------------------------------------------------------------------===//
1386
1387
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001388namespace {
1389/// X86_64ABIInfo - The X86_64 ABI information.
1390class X86_64ABIInfo : public ABIInfo {
1391 enum Class {
1392 Integer = 0,
1393 SSE,
1394 SSEUp,
1395 X87,
1396 X87Up,
1397 ComplexX87,
1398 NoClass,
1399 Memory
1400 };
1401
1402 /// merge - Implement the X86_64 ABI merging algorithm.
1403 ///
1404 /// Merge an accumulating classification \arg Accum with a field
1405 /// classification \arg Field.
1406 ///
1407 /// \param Accum - The accumulating classification. This should
1408 /// always be either NoClass or the result of a previous merge
1409 /// call. In addition, this should never be Memory (the caller
1410 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001411 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001412
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001413 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1414 ///
1415 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1416 /// final MEMORY or SSE classes when necessary.
1417 ///
1418 /// \param AggregateSize - The size of the current aggregate in
1419 /// the classification process.
1420 ///
1421 /// \param Lo - The classification for the parts of the type
1422 /// residing in the low word of the containing object.
1423 ///
1424 /// \param Hi - The classification for the parts of the type
1425 /// residing in the higher words of the containing object.
1426 ///
1427 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1428
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001429 /// classify - Determine the x86_64 register classes in which the
1430 /// given type T should be passed.
1431 ///
1432 /// \param Lo - The classification for the parts of the type
1433 /// residing in the low word of the containing object.
1434 ///
1435 /// \param Hi - The classification for the parts of the type
1436 /// residing in the high word of the containing object.
1437 ///
1438 /// \param OffsetBase - The bit offset of this type in the
1439 /// containing object. Some parameters are classified different
1440 /// depending on whether they straddle an eightbyte boundary.
1441 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001442 /// \param isNamedArg - Whether the argument in question is a "named"
1443 /// argument, as used in AMD64-ABI 3.5.7.
1444 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001445 /// If a word is unused its result will be NoClass; if a type should
1446 /// be passed in Memory then at least the classification of \arg Lo
1447 /// will be Memory.
1448 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001449 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001450 ///
1451 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1452 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001453 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1454 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001455
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001456 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001457 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1458 unsigned IROffset, QualType SourceTy,
1459 unsigned SourceOffset) const;
1460 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1461 unsigned IROffset, QualType SourceTy,
1462 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001463
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001464 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001465 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001466 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001467
1468 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001469 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001470 ///
1471 /// \param freeIntRegs - The number of free integer registers remaining
1472 /// available.
1473 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001474
Chris Lattner458b2aa2010-07-29 02:16:43 +00001475 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001476
Bill Wendling5cd41c42010-10-18 03:41:31 +00001477 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001478 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001479 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001480 unsigned &neededSSE,
1481 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001482
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001483 bool IsIllegalVectorType(QualType Ty) const;
1484
John McCalle0fda732011-04-21 01:20:55 +00001485 /// The 0.98 ABI revision clarified a lot of ambiguities,
1486 /// unfortunately in ways that were not always consistent with
1487 /// certain previous compilers. In particular, platforms which
1488 /// required strict binary compatibility with older versions of GCC
1489 /// may need to exempt themselves.
1490 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001491 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001492 }
1493
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001494 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001495 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1496 // 64-bit hardware.
1497 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001498
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001499public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001500 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001501 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001502 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001503 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001504
John McCalla729c622012-02-17 03:33:10 +00001505 bool isPassedUsingAVXType(QualType type) const {
1506 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001507 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001508 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1509 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001510 if (info.isDirect()) {
1511 llvm::Type *ty = info.getCoerceToType();
1512 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1513 return (vectorTy->getBitWidth() > 128);
1514 }
1515 return false;
1516 }
1517
Craig Topper4f12f102014-03-12 06:41:41 +00001518 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001519
Craig Topper4f12f102014-03-12 06:41:41 +00001520 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1521 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001522
1523 bool has64BitPointers() const {
1524 return Has64BitPointers;
1525 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001526};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001527
Chris Lattner04dc9572010-08-31 16:44:54 +00001528/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001529class WinX86_64ABIInfo : public ABIInfo {
1530
Reid Kleckner80944df2014-10-31 22:00:51 +00001531 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1532 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001533
Chris Lattner04dc9572010-08-31 16:44:54 +00001534public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001535 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1536
Craig Topper4f12f102014-03-12 06:41:41 +00001537 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001538
Craig Topper4f12f102014-03-12 06:41:41 +00001539 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1540 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001541
1542 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1543 // FIXME: Assumes vectorcall is in use.
1544 return isX86VectorTypeForVectorCall(getContext(), Ty);
1545 }
1546
1547 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1548 uint64_t NumMembers) const override {
1549 // FIXME: Assumes vectorcall is in use.
1550 return isX86VectorCallAggregateSmallEnough(NumMembers);
1551 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001552};
1553
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001554class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001555 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001556public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001557 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001558 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001559
John McCalla729c622012-02-17 03:33:10 +00001560 const X86_64ABIInfo &getABIInfo() const {
1561 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1562 }
1563
Craig Topper4f12f102014-03-12 06:41:41 +00001564 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001565 return 7;
1566 }
1567
1568 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001569 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001570 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001571
John McCall943fae92010-05-27 06:19:26 +00001572 // 0-15 are the 16 integer registers.
1573 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001574 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001575 return false;
1576 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001577
Jay Foad7c57be32011-07-11 09:56:20 +00001578 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001579 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001580 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001581 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1582 }
1583
John McCalla729c622012-02-17 03:33:10 +00001584 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001585 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001586 // The default CC on x86-64 sets %al to the number of SSA
1587 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001588 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001589 // that when AVX types are involved: the ABI explicitly states it is
1590 // undefined, and it doesn't work in practice because of how the ABI
1591 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001592 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001593 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001594 for (CallArgList::const_iterator
1595 it = args.begin(), ie = args.end(); it != ie; ++it) {
1596 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1597 HasAVXType = true;
1598 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001599 }
1600 }
John McCalla729c622012-02-17 03:33:10 +00001601
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001602 if (!HasAVXType)
1603 return true;
1604 }
John McCallcbc038a2011-09-21 08:08:30 +00001605
John McCalla729c622012-02-17 03:33:10 +00001606 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001607 }
1608
Craig Topper4f12f102014-03-12 06:41:41 +00001609 llvm::Constant *
1610 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001611 unsigned Sig;
1612 if (getABIInfo().has64BitPointers())
1613 Sig = (0xeb << 0) | // jmp rel8
1614 (0x0a << 8) | // .+0x0c
1615 ('F' << 16) |
1616 ('T' << 24);
1617 else
1618 Sig = (0xeb << 0) | // jmp rel8
1619 (0x06 << 8) | // .+0x08
1620 ('F' << 16) |
1621 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001622 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1623 }
1624
Alexander Musman09184fe2014-09-30 05:29:28 +00001625 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1626 return HasAVX ? 32 : 16;
1627 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001628};
1629
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001630class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1631public:
1632 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1633 : X86_64TargetCodeGenInfo(CGT, HasAVX) {}
1634
1635 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001636 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001637 Opt = "\01";
1638 Opt += Lib;
1639 }
1640};
1641
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001642static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001643 // If the argument does not end in .lib, automatically add the suffix.
1644 // If the argument contains a space, enclose it in quotes.
1645 // This matches the behavior of MSVC.
1646 bool Quote = (Lib.find(" ") != StringRef::npos);
1647 std::string ArgStr = Quote ? "\"" : "";
1648 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001649 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001650 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001651 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001652 return ArgStr;
1653}
1654
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001655class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1656public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001657 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1658 bool d, bool p, bool w, unsigned RegParms)
1659 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001660
Hans Wennborg77dc2362015-01-20 19:45:50 +00001661 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1662 CodeGen::CodeGenModule &CGM) const override;
1663
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001664 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001665 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001666 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001667 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001668 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001669
1670 void getDetectMismatchOption(llvm::StringRef Name,
1671 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001672 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001673 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001674 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001675};
1676
Hans Wennborg77dc2362015-01-20 19:45:50 +00001677static void addStackProbeSizeTargetAttribute(const Decl *D,
1678 llvm::GlobalValue *GV,
1679 CodeGen::CodeGenModule &CGM) {
1680 if (isa<FunctionDecl>(D)) {
1681 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1682 llvm::Function *Fn = cast<llvm::Function>(GV);
1683
1684 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1685 }
1686 }
1687}
1688
1689void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1690 llvm::GlobalValue *GV,
1691 CodeGen::CodeGenModule &CGM) const {
1692 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1693
1694 addStackProbeSizeTargetAttribute(D, GV, CGM);
1695}
1696
Chris Lattner04dc9572010-08-31 16:44:54 +00001697class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001698 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001699public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001700 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1701 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001702
Hans Wennborg77dc2362015-01-20 19:45:50 +00001703 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1704 CodeGen::CodeGenModule &CGM) const override;
1705
Craig Topper4f12f102014-03-12 06:41:41 +00001706 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001707 return 7;
1708 }
1709
1710 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001711 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001712 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001713
Chris Lattner04dc9572010-08-31 16:44:54 +00001714 // 0-15 are the 16 integer registers.
1715 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001716 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001717 return false;
1718 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001719
1720 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001721 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001722 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001723 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001724 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001725
1726 void getDetectMismatchOption(llvm::StringRef Name,
1727 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001728 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001729 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001730 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001731
1732 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1733 return HasAVX ? 32 : 16;
1734 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001735};
1736
Hans Wennborg77dc2362015-01-20 19:45:50 +00001737void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1738 llvm::GlobalValue *GV,
1739 CodeGen::CodeGenModule &CGM) const {
1740 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1741
1742 addStackProbeSizeTargetAttribute(D, GV, CGM);
1743}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001744}
1745
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001746void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1747 Class &Hi) const {
1748 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1749 //
1750 // (a) If one of the classes is Memory, the whole argument is passed in
1751 // memory.
1752 //
1753 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1754 // memory.
1755 //
1756 // (c) If the size of the aggregate exceeds two eightbytes and the first
1757 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1758 // argument is passed in memory. NOTE: This is necessary to keep the
1759 // ABI working for processors that don't support the __m256 type.
1760 //
1761 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1762 //
1763 // Some of these are enforced by the merging logic. Others can arise
1764 // only with unions; for example:
1765 // union { _Complex double; unsigned; }
1766 //
1767 // Note that clauses (b) and (c) were added in 0.98.
1768 //
1769 if (Hi == Memory)
1770 Lo = Memory;
1771 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1772 Lo = Memory;
1773 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1774 Lo = Memory;
1775 if (Hi == SSEUp && Lo != SSE)
1776 Hi = SSE;
1777}
1778
Chris Lattnerd776fb12010-06-28 21:43:59 +00001779X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001780 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1781 // classified recursively so that always two fields are
1782 // considered. The resulting class is calculated according to
1783 // the classes of the fields in the eightbyte:
1784 //
1785 // (a) If both classes are equal, this is the resulting class.
1786 //
1787 // (b) If one of the classes is NO_CLASS, the resulting class is
1788 // the other class.
1789 //
1790 // (c) If one of the classes is MEMORY, the result is the MEMORY
1791 // class.
1792 //
1793 // (d) If one of the classes is INTEGER, the result is the
1794 // INTEGER.
1795 //
1796 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1797 // MEMORY is used as class.
1798 //
1799 // (f) Otherwise class SSE is used.
1800
1801 // Accum should never be memory (we should have returned) or
1802 // ComplexX87 (because this cannot be passed in a structure).
1803 assert((Accum != Memory && Accum != ComplexX87) &&
1804 "Invalid accumulated classification during merge.");
1805 if (Accum == Field || Field == NoClass)
1806 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001807 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001808 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001809 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001810 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001811 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001812 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001813 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1814 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001815 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001816 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001817}
1818
Chris Lattner5c740f12010-06-30 19:14:05 +00001819void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001820 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001821 // FIXME: This code can be simplified by introducing a simple value class for
1822 // Class pairs with appropriate constructor methods for the various
1823 // situations.
1824
1825 // FIXME: Some of the split computations are wrong; unaligned vectors
1826 // shouldn't be passed in registers for example, so there is no chance they
1827 // can straddle an eightbyte. Verify & simplify.
1828
1829 Lo = Hi = NoClass;
1830
1831 Class &Current = OffsetBase < 64 ? Lo : Hi;
1832 Current = Memory;
1833
John McCall9dd450b2009-09-21 23:43:11 +00001834 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001835 BuiltinType::Kind k = BT->getKind();
1836
1837 if (k == BuiltinType::Void) {
1838 Current = NoClass;
1839 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1840 Lo = Integer;
1841 Hi = Integer;
1842 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1843 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001844 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1845 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001846 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001847 Current = SSE;
1848 } else if (k == BuiltinType::LongDouble) {
1849 Lo = X87;
1850 Hi = X87Up;
1851 }
1852 // FIXME: _Decimal32 and _Decimal64 are SSE.
1853 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001854 return;
1855 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001856
Chris Lattnerd776fb12010-06-28 21:43:59 +00001857 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001858 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001859 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001860 return;
1861 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001862
Chris Lattnerd776fb12010-06-28 21:43:59 +00001863 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001864 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001865 return;
1866 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001867
Chris Lattnerd776fb12010-06-28 21:43:59 +00001868 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001869 if (Ty->isMemberFunctionPointerType()) {
1870 if (Has64BitPointers) {
1871 // If Has64BitPointers, this is an {i64, i64}, so classify both
1872 // Lo and Hi now.
1873 Lo = Hi = Integer;
1874 } else {
1875 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1876 // straddles an eightbyte boundary, Hi should be classified as well.
1877 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1878 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1879 if (EB_FuncPtr != EB_ThisAdj) {
1880 Lo = Hi = Integer;
1881 } else {
1882 Current = Integer;
1883 }
1884 }
1885 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001886 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001887 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001888 return;
1889 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001890
Chris Lattnerd776fb12010-06-28 21:43:59 +00001891 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001892 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001893 if (Size == 32) {
1894 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1895 // float> as integer.
1896 Current = Integer;
1897
1898 // If this type crosses an eightbyte boundary, it should be
1899 // split.
1900 uint64_t EB_Real = (OffsetBase) / 64;
1901 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1902 if (EB_Real != EB_Imag)
1903 Hi = Lo;
1904 } else if (Size == 64) {
1905 // gcc passes <1 x double> in memory. :(
1906 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1907 return;
1908
1909 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001910 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001911 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1912 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1913 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001914 Current = Integer;
1915 else
1916 Current = SSE;
1917
1918 // If this type crosses an eightbyte boundary, it should be
1919 // split.
1920 if (OffsetBase && OffsetBase != 64)
1921 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001922 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001923 // Arguments of 256-bits are split into four eightbyte chunks. The
1924 // least significant one belongs to class SSE and all the others to class
1925 // SSEUP. The original Lo and Hi design considers that types can't be
1926 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1927 // This design isn't correct for 256-bits, but since there're no cases
1928 // where the upper parts would need to be inspected, avoid adding
1929 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001930 //
1931 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1932 // registers if they are "named", i.e. not part of the "..." of a
1933 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001934 Lo = SSE;
1935 Hi = SSEUp;
1936 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001937 return;
1938 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001939
Chris Lattnerd776fb12010-06-28 21:43:59 +00001940 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001941 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001942
Chris Lattner2b037972010-07-29 02:01:43 +00001943 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001944 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001945 if (Size <= 64)
1946 Current = Integer;
1947 else if (Size <= 128)
1948 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001949 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001950 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001951 else if (ET == getContext().DoubleTy ||
1952 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001953 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001954 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001955 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001956 Current = ComplexX87;
1957
1958 // If this complex type crosses an eightbyte boundary then it
1959 // should be split.
1960 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001961 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001962 if (Hi == NoClass && EB_Real != EB_Imag)
1963 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001964
Chris Lattnerd776fb12010-06-28 21:43:59 +00001965 return;
1966 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001967
Chris Lattner2b037972010-07-29 02:01:43 +00001968 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001969 // Arrays are treated like structures.
1970
Chris Lattner2b037972010-07-29 02:01:43 +00001971 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001972
1973 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001974 // than four eightbytes, ..., it has class MEMORY.
1975 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001976 return;
1977
1978 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1979 // fields, it has class MEMORY.
1980 //
1981 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001982 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001983 return;
1984
1985 // Otherwise implement simplified merge. We could be smarter about
1986 // this, but it isn't worth it and would be harder to verify.
1987 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001988 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001989 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001990
1991 // The only case a 256-bit wide vector could be used is when the array
1992 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1993 // to work for sizes wider than 128, early check and fallback to memory.
1994 if (Size > 128 && EltSize != 256)
1995 return;
1996
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001997 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1998 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001999 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002000 Lo = merge(Lo, FieldLo);
2001 Hi = merge(Hi, FieldHi);
2002 if (Lo == Memory || Hi == Memory)
2003 break;
2004 }
2005
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002006 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002007 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002008 return;
2009 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002010
Chris Lattnerd776fb12010-06-28 21:43:59 +00002011 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002012 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002013
2014 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002015 // than four eightbytes, ..., it has class MEMORY.
2016 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002017 return;
2018
Anders Carlsson20759ad2009-09-16 15:53:40 +00002019 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2020 // copy constructor or a non-trivial destructor, it is passed by invisible
2021 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002022 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002023 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002024
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002025 const RecordDecl *RD = RT->getDecl();
2026
2027 // Assume variable sized types are passed in memory.
2028 if (RD->hasFlexibleArrayMember())
2029 return;
2030
Chris Lattner2b037972010-07-29 02:01:43 +00002031 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002032
2033 // Reset Lo class, this will be recomputed.
2034 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002035
2036 // If this is a C++ record, classify the bases first.
2037 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002038 for (const auto &I : CXXRD->bases()) {
2039 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002040 "Unexpected base class!");
2041 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002042 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002043
2044 // Classify this field.
2045 //
2046 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2047 // single eightbyte, each is classified separately. Each eightbyte gets
2048 // initialized to class NO_CLASS.
2049 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002050 uint64_t Offset =
2051 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002052 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002053 Lo = merge(Lo, FieldLo);
2054 Hi = merge(Hi, FieldHi);
2055 if (Lo == Memory || Hi == Memory)
2056 break;
2057 }
2058 }
2059
2060 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002061 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002062 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002063 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002064 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2065 bool BitField = i->isBitField();
2066
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002067 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2068 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002069 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002070 // The only case a 256-bit wide vector could be used is when the struct
2071 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2072 // to work for sizes wider than 128, early check and fallback to memory.
2073 //
2074 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2075 Lo = Memory;
2076 return;
2077 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002078 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002079 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002080 Lo = Memory;
2081 return;
2082 }
2083
2084 // Classify this field.
2085 //
2086 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2087 // exceeds a single eightbyte, each is classified
2088 // separately. Each eightbyte gets initialized to class
2089 // NO_CLASS.
2090 Class FieldLo, FieldHi;
2091
2092 // Bit-fields require special handling, they do not force the
2093 // structure to be passed in memory even if unaligned, and
2094 // therefore they can straddle an eightbyte.
2095 if (BitField) {
2096 // Ignore padding bit-fields.
2097 if (i->isUnnamedBitfield())
2098 continue;
2099
2100 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002101 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002102
2103 uint64_t EB_Lo = Offset / 64;
2104 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002105
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002106 if (EB_Lo) {
2107 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2108 FieldLo = NoClass;
2109 FieldHi = Integer;
2110 } else {
2111 FieldLo = Integer;
2112 FieldHi = EB_Hi ? Integer : NoClass;
2113 }
2114 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002115 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002116 Lo = merge(Lo, FieldLo);
2117 Hi = merge(Hi, FieldHi);
2118 if (Lo == Memory || Hi == Memory)
2119 break;
2120 }
2121
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002122 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002123 }
2124}
2125
Chris Lattner22a931e2010-06-29 06:01:59 +00002126ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002127 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2128 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002129 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002130 // Treat an enum type as its underlying type.
2131 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2132 Ty = EnumTy->getDecl()->getIntegerType();
2133
2134 return (Ty->isPromotableIntegerType() ?
2135 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2136 }
2137
2138 return ABIArgInfo::getIndirect(0);
2139}
2140
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002141bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2142 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2143 uint64_t Size = getContext().getTypeSize(VecTy);
2144 unsigned LargestVector = HasAVX ? 256 : 128;
2145 if (Size <= 64 || Size > LargestVector)
2146 return true;
2147 }
2148
2149 return false;
2150}
2151
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002152ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2153 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002154 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2155 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002156 //
2157 // This assumption is optimistic, as there could be free registers available
2158 // when we need to pass this argument in memory, and LLVM could try to pass
2159 // the argument in the free register. This does not seem to happen currently,
2160 // but this code would be much safer if we could mark the argument with
2161 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002162 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002163 // Treat an enum type as its underlying type.
2164 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2165 Ty = EnumTy->getDecl()->getIntegerType();
2166
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002167 return (Ty->isPromotableIntegerType() ?
2168 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002169 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002170
Mark Lacey3825e832013-10-06 01:33:34 +00002171 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002172 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002173
Chris Lattner44c2b902011-05-22 23:21:23 +00002174 // Compute the byval alignment. We specify the alignment of the byval in all
2175 // cases so that the mid-level optimizer knows the alignment of the byval.
2176 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002177
2178 // Attempt to avoid passing indirect results using byval when possible. This
2179 // is important for good codegen.
2180 //
2181 // We do this by coercing the value into a scalar type which the backend can
2182 // handle naturally (i.e., without using byval).
2183 //
2184 // For simplicity, we currently only do this when we have exhausted all of the
2185 // free integer registers. Doing this when there are free integer registers
2186 // would require more care, as we would have to ensure that the coerced value
2187 // did not claim the unused register. That would require either reording the
2188 // arguments to the function (so that any subsequent inreg values came first),
2189 // or only doing this optimization when there were no following arguments that
2190 // might be inreg.
2191 //
2192 // We currently expect it to be rare (particularly in well written code) for
2193 // arguments to be passed on the stack when there are still free integer
2194 // registers available (this would typically imply large structs being passed
2195 // by value), so this seems like a fair tradeoff for now.
2196 //
2197 // We can revisit this if the backend grows support for 'onstack' parameter
2198 // attributes. See PR12193.
2199 if (freeIntRegs == 0) {
2200 uint64_t Size = getContext().getTypeSize(Ty);
2201
2202 // If this type fits in an eightbyte, coerce it into the matching integral
2203 // type, which will end up on the stack (with alignment 8).
2204 if (Align == 8 && Size <= 64)
2205 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2206 Size));
2207 }
2208
Chris Lattner44c2b902011-05-22 23:21:23 +00002209 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002210}
2211
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002212/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2213/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002214llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002215 // Wrapper structs/arrays that only contain vectors are passed just like
2216 // vectors; strip them off if present.
2217 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2218 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002219
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002220 llvm::Type *IRType = CGT.ConvertType(Ty);
Benjamin Kramer83b1bf32015-03-02 16:09:24 +00002221 assert(isa<llvm::VectorType>(IRType) &&
2222 "Trying to return a non-vector type in a vector register!");
2223 return IRType;
Chris Lattner4200fe42010-07-29 04:56:46 +00002224}
2225
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002226/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2227/// is known to either be off the end of the specified type or being in
2228/// alignment padding. The user type specified is known to be at most 128 bits
2229/// in size, and have passed through X86_64ABIInfo::classify with a successful
2230/// classification that put one of the two halves in the INTEGER class.
2231///
2232/// It is conservatively correct to return false.
2233static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2234 unsigned EndBit, ASTContext &Context) {
2235 // If the bytes being queried are off the end of the type, there is no user
2236 // data hiding here. This handles analysis of builtins, vectors and other
2237 // types that don't contain interesting padding.
2238 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2239 if (TySize <= StartBit)
2240 return true;
2241
Chris Lattner98076a22010-07-29 07:43:55 +00002242 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2243 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2244 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2245
2246 // Check each element to see if the element overlaps with the queried range.
2247 for (unsigned i = 0; i != NumElts; ++i) {
2248 // If the element is after the span we care about, then we're done..
2249 unsigned EltOffset = i*EltSize;
2250 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002251
Chris Lattner98076a22010-07-29 07:43:55 +00002252 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2253 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2254 EndBit-EltOffset, Context))
2255 return false;
2256 }
2257 // If it overlaps no elements, then it is safe to process as padding.
2258 return true;
2259 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002260
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002261 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2262 const RecordDecl *RD = RT->getDecl();
2263 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002264
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002265 // If this is a C++ record, check the bases first.
2266 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002267 for (const auto &I : CXXRD->bases()) {
2268 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002269 "Unexpected base class!");
2270 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002271 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002272
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002273 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002274 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002275 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002276
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002277 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002278 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002279 EndBit-BaseOffset, Context))
2280 return false;
2281 }
2282 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002283
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002284 // Verify that no field has data that overlaps the region of interest. Yes
2285 // this could be sped up a lot by being smarter about queried fields,
2286 // however we're only looking at structs up to 16 bytes, so we don't care
2287 // much.
2288 unsigned idx = 0;
2289 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2290 i != e; ++i, ++idx) {
2291 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002292
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002293 // If we found a field after the region we care about, then we're done.
2294 if (FieldOffset >= EndBit) break;
2295
2296 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2297 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2298 Context))
2299 return false;
2300 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002301
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002302 // If nothing in this record overlapped the area of interest, then we're
2303 // clean.
2304 return true;
2305 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002306
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002307 return false;
2308}
2309
Chris Lattnere556a712010-07-29 18:39:32 +00002310/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2311/// float member at the specified offset. For example, {int,{float}} has a
2312/// float at offset 4. It is conservatively correct for this routine to return
2313/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002314static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002315 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002316 // Base case if we find a float.
2317 if (IROffset == 0 && IRType->isFloatTy())
2318 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002319
Chris Lattnere556a712010-07-29 18:39:32 +00002320 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002321 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002322 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2323 unsigned Elt = SL->getElementContainingOffset(IROffset);
2324 IROffset -= SL->getElementOffset(Elt);
2325 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2326 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002327
Chris Lattnere556a712010-07-29 18:39:32 +00002328 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002329 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2330 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002331 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2332 IROffset -= IROffset/EltSize*EltSize;
2333 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2334 }
2335
2336 return false;
2337}
2338
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002339
2340/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2341/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002342llvm::Type *X86_64ABIInfo::
2343GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002344 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002345 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002346 // pass as float if the last 4 bytes is just padding. This happens for
2347 // structs that contain 3 floats.
2348 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2349 SourceOffset*8+64, getContext()))
2350 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002351
Chris Lattnere556a712010-07-29 18:39:32 +00002352 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2353 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2354 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002355 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2356 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002357 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002358
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002359 return llvm::Type::getDoubleTy(getVMContext());
2360}
2361
2362
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002363/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2364/// an 8-byte GPR. This means that we either have a scalar or we are talking
2365/// about the high or low part of an up-to-16-byte struct. This routine picks
2366/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002367/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2368/// etc).
2369///
2370/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2371/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2372/// the 8-byte value references. PrefType may be null.
2373///
Alp Toker9907f082014-07-09 14:06:35 +00002374/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002375/// an offset into this that we're processing (which is always either 0 or 8).
2376///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002377llvm::Type *X86_64ABIInfo::
2378GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002379 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002380 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2381 // returning an 8-byte unit starting with it. See if we can safely use it.
2382 if (IROffset == 0) {
2383 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002384 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2385 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002386 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002387
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002388 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2389 // goodness in the source type is just tail padding. This is allowed to
2390 // kick in for struct {double,int} on the int, but not on
2391 // struct{double,int,int} because we wouldn't return the second int. We
2392 // have to do this analysis on the source type because we can't depend on
2393 // unions being lowered a specific way etc.
2394 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002395 IRType->isIntegerTy(32) ||
2396 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2397 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2398 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002399
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002400 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2401 SourceOffset*8+64, getContext()))
2402 return IRType;
2403 }
2404 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002405
Chris Lattner2192fe52011-07-18 04:24:23 +00002406 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002407 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002408 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002409 if (IROffset < SL->getSizeInBytes()) {
2410 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2411 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002412
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002413 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2414 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002415 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002416 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002417
Chris Lattner2192fe52011-07-18 04:24:23 +00002418 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002419 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002420 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002421 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002422 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2423 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002424 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002425
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002426 // Okay, we don't have any better idea of what to pass, so we pass this in an
2427 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002428 unsigned TySizeInBytes =
2429 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002430
Chris Lattner3f763422010-07-29 17:34:39 +00002431 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002432
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002433 // It is always safe to classify this as an integer type up to i64 that
2434 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002435 return llvm::IntegerType::get(getVMContext(),
2436 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002437}
2438
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002439
2440/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2441/// be used as elements of a two register pair to pass or return, return a
2442/// first class aggregate to represent them. For example, if the low part of
2443/// a by-value argument should be passed as i32* and the high part as float,
2444/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002445static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002446GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002447 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002448 // In order to correctly satisfy the ABI, we need to the high part to start
2449 // at offset 8. If the high and low parts we inferred are both 4-byte types
2450 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2451 // the second element at offset 8. Check for this:
2452 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2453 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002454 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002455 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002456
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002457 // To handle this, we have to increase the size of the low part so that the
2458 // second element will start at an 8 byte offset. We can't increase the size
2459 // of the second element because it might make us access off the end of the
2460 // struct.
2461 if (HiStart != 8) {
2462 // There are only two sorts of types the ABI generation code can produce for
2463 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2464 // Promote these to a larger type.
2465 if (Lo->isFloatTy())
2466 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2467 else {
2468 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2469 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2470 }
2471 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002472
Reid Kleckneree7cf842014-12-01 22:02:27 +00002473 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002474
2475
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002476 // Verify that the second element is at an 8-byte offset.
2477 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2478 "Invalid x86-64 argument pair!");
2479 return Result;
2480}
2481
Chris Lattner31faff52010-07-28 23:06:14 +00002482ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002483classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002484 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2485 // classification algorithm.
2486 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002487 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002488
2489 // Check some invariants.
2490 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002491 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2492
Craig Topper8a13c412014-05-21 05:09:00 +00002493 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002494 switch (Lo) {
2495 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002496 if (Hi == NoClass)
2497 return ABIArgInfo::getIgnore();
2498 // If the low part is just padding, it takes no register, leave ResType
2499 // null.
2500 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2501 "Unknown missing lo part");
2502 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002503
2504 case SSEUp:
2505 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002506 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002507
2508 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2509 // hidden argument.
2510 case Memory:
2511 return getIndirectReturnResult(RetTy);
2512
2513 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2514 // available register of the sequence %rax, %rdx is used.
2515 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002516 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002517
Chris Lattner1f3a0632010-07-29 21:42:50 +00002518 // If we have a sign or zero extended integer, make sure to return Extend
2519 // so that the parameter gets the right LLVM IR attributes.
2520 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2521 // Treat an enum type as its underlying type.
2522 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2523 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002524
Chris Lattner1f3a0632010-07-29 21:42:50 +00002525 if (RetTy->isIntegralOrEnumerationType() &&
2526 RetTy->isPromotableIntegerType())
2527 return ABIArgInfo::getExtend();
2528 }
Chris Lattner31faff52010-07-28 23:06:14 +00002529 break;
2530
2531 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2532 // available SSE register of the sequence %xmm0, %xmm1 is used.
2533 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002534 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002535 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002536
2537 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2538 // returned on the X87 stack in %st0 as 80-bit x87 number.
2539 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002540 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002541 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002542
2543 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2544 // part of the value is returned in %st0 and the imaginary part in
2545 // %st1.
2546 case ComplexX87:
2547 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002548 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002549 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002550 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002551 break;
2552 }
2553
Craig Topper8a13c412014-05-21 05:09:00 +00002554 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002555 switch (Hi) {
2556 // Memory was handled previously and X87 should
2557 // never occur as a hi class.
2558 case Memory:
2559 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002560 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002561
2562 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002563 case NoClass:
2564 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002565
Chris Lattner52b3c132010-09-01 00:20:33 +00002566 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002567 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002568 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2569 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002570 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002571 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002572 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002573 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2574 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002575 break;
2576
2577 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002578 // is passed in the next available eightbyte chunk if the last used
2579 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002580 //
Chris Lattner57540c52011-04-15 05:22:18 +00002581 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002582 case SSEUp:
2583 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002584 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002585 break;
2586
2587 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2588 // returned together with the previous X87 value in %st0.
2589 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002590 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002591 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002592 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002593 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002594 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002595 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002596 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2597 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002598 }
Chris Lattner31faff52010-07-28 23:06:14 +00002599 break;
2600 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002601
Chris Lattner52b3c132010-09-01 00:20:33 +00002602 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002603 // known to pass in the high eightbyte of the result. We do this by forming a
2604 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002605 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002606 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002607
Chris Lattner1f3a0632010-07-29 21:42:50 +00002608 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002609}
2610
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002611ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002612 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2613 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002614 const
2615{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002616 Ty = useFirstFieldIfTransparentUnion(Ty);
2617
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002619 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002620
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 // Check some invariants.
2622 // FIXME: Enforce these by construction.
2623 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002624 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2625
2626 neededInt = 0;
2627 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002628 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 switch (Lo) {
2630 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002631 if (Hi == NoClass)
2632 return ABIArgInfo::getIgnore();
2633 // If the low part is just padding, it takes no register, leave ResType
2634 // null.
2635 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2636 "Unknown missing lo part");
2637 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002638
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2640 // on the stack.
2641 case Memory:
2642
2643 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2644 // COMPLEX_X87, it is passed in memory.
2645 case X87:
2646 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002647 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002648 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002649 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002650
2651 case SSEUp:
2652 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002653 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002654
2655 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2656 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2657 // and %r9 is used.
2658 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002659 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002660
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002661 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002662 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002663
2664 // If we have a sign or zero extended integer, make sure to return Extend
2665 // so that the parameter gets the right LLVM IR attributes.
2666 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2667 // Treat an enum type as its underlying type.
2668 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2669 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002670
Chris Lattner1f3a0632010-07-29 21:42:50 +00002671 if (Ty->isIntegralOrEnumerationType() &&
2672 Ty->isPromotableIntegerType())
2673 return ABIArgInfo::getExtend();
2674 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002675
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002676 break;
2677
2678 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2679 // available SSE register is used, the registers are taken in the
2680 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002681 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002682 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002683 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002684 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 break;
2686 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002687 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688
Craig Topper8a13c412014-05-21 05:09:00 +00002689 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 switch (Hi) {
2691 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002692 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 // which is passed in memory.
2694 case Memory:
2695 case X87:
2696 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002697 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698
2699 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002700
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002701 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002702 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002703 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002704 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002705
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002706 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2707 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708 break;
2709
2710 // X87Up generally doesn't occur here (long double is passed in
2711 // memory), except in situations involving unions.
2712 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002713 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002714 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002715
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002716 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2717 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002718
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719 ++neededSSE;
2720 break;
2721
2722 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2723 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002724 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002725 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002726 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002727 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002728 break;
2729 }
2730
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002731 // If a high part was specified, merge it together with the low part. It is
2732 // known to pass in the high eightbyte of the result. We do this by forming a
2733 // first class struct aggregate with the high and low part: {low, high}
2734 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002735 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002736
Chris Lattner1f3a0632010-07-29 21:42:50 +00002737 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738}
2739
Chris Lattner22326a12010-07-29 02:31:05 +00002740void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002741
Reid Kleckner40ca9132014-05-13 22:05:45 +00002742 if (!getCXXABI().classifyReturnType(FI))
2743 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744
2745 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002746 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747
2748 // If the return value is indirect, then the hidden argument is consuming one
2749 // integer register.
2750 if (FI.getReturnInfo().isIndirect())
2751 --freeIntRegs;
2752
Peter Collingbournef7706832014-12-12 23:41:25 +00002753 // The chain argument effectively gives us another free register.
2754 if (FI.isChainCall())
2755 ++freeIntRegs;
2756
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002757 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002758 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2759 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002760 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002761 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002762 it != ie; ++it, ++ArgNo) {
2763 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002764
Bill Wendling9987c0e2010-10-18 23:51:38 +00002765 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002766 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002767 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002768
2769 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2770 // eightbyte of an argument, the whole argument is passed on the
2771 // stack. If registers have already been assigned for some
2772 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002773 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002774 freeIntRegs -= neededInt;
2775 freeSSERegs -= neededSSE;
2776 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002777 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002778 }
2779 }
2780}
2781
2782static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2783 QualType Ty,
2784 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002785 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2786 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002787 llvm::Value *overflow_arg_area =
2788 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2789
2790 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2791 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002792 // It isn't stated explicitly in the standard, but in practice we use
2793 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2795 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002796 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002797 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002798 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002799 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2800 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002801 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002802 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 overflow_arg_area =
2804 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2805 overflow_arg_area->getType(),
2806 "overflow_arg_area.align");
2807 }
2808
2809 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002810 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002811 llvm::Value *Res =
2812 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002813 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814
2815 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2816 // l->overflow_arg_area + sizeof(type).
2817 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2818 // an 8 byte boundary.
2819
2820 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002821 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002822 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002823 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2824 "overflow_arg_area.next");
2825 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2826
2827 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2828 return Res;
2829}
2830
2831llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2832 CodeGenFunction &CGF) const {
2833 // Assume that va_list type is correct; should be pointer to LLVM type:
2834 // struct {
2835 // i32 gp_offset;
2836 // i32 fp_offset;
2837 // i8* overflow_arg_area;
2838 // i8* reg_save_area;
2839 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002840 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002841
Chris Lattner9723d6c2010-03-11 18:19:55 +00002842 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002843 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2844 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002845
2846 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2847 // in the registers. If not go to step 7.
2848 if (!neededInt && !neededSSE)
2849 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2850
2851 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2852 // general purpose registers needed to pass type and num_fp to hold
2853 // the number of floating point registers needed.
2854
2855 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2856 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2857 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2858 //
2859 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2860 // register save space).
2861
Craig Topper8a13c412014-05-21 05:09:00 +00002862 llvm::Value *InRegs = nullptr;
2863 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2864 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002865 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002866 gp_offset_p =
2867 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002868 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002869 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2870 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002871 }
2872
2873 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002874 fp_offset_p =
2875 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002876 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2877 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002878 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2879 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002880 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2881 }
2882
2883 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2884 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2885 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2886 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2887
2888 // Emit code to load the value if it was passed in registers.
2889
2890 CGF.EmitBlock(InRegBlock);
2891
2892 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2893 // an offset of l->gp_offset and/or l->fp_offset. This may require
2894 // copying to a temporary location in case the parameter is passed
2895 // in different register classes or requires an alignment greater
2896 // than 8 for general purpose registers and 16 for XMM registers.
2897 //
2898 // FIXME: This really results in shameful code when we end up needing to
2899 // collect arguments from different places; often what should result in a
2900 // simple assembling of a structure from scattered addresses has many more
2901 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002902 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002903 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2904 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002905 if (neededInt && neededSSE) {
2906 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002907 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002908 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002909 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2910 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002911 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002912 llvm::Type *TyLo = ST->getElementType(0);
2913 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002914 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002915 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002916 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2917 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002918 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2919 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002920 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2921 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002922 llvm::Value *V =
2923 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002924 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002925 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002926 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002927
Owen Anderson170229f2009-07-14 23:10:40 +00002928 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002929 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002930 } else if (neededInt) {
2931 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2932 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002933 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002934
2935 // Copy to a temporary if necessary to ensure the appropriate alignment.
2936 std::pair<CharUnits, CharUnits> SizeAlign =
2937 CGF.getContext().getTypeInfoInChars(Ty);
2938 uint64_t TySize = SizeAlign.first.getQuantity();
2939 unsigned TyAlign = SizeAlign.second.getQuantity();
2940 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002941 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2942 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2943 RegAddr = Tmp;
2944 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002945 } else if (neededSSE == 1) {
2946 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2947 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2948 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002949 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002950 assert(neededSSE == 2 && "Invalid number of needed registers!");
2951 // SSE registers are spaced 16 bytes apart in the register save
2952 // area, we need to collect the two eightbytes together.
2953 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002954 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002955 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002956 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002957 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002958 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002959 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2960 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002961 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2962 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002963 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00002964 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2965 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00002966 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00002967 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2968 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002969 }
2970
2971 // AMD64-ABI 3.5.7p5: Step 5. Set:
2972 // l->gp_offset = l->gp_offset + num_gp * 8
2973 // l->fp_offset = l->fp_offset + num_fp * 16.
2974 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002975 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002976 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2977 gp_offset_p);
2978 }
2979 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002980 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002981 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2982 fp_offset_p);
2983 }
2984 CGF.EmitBranch(ContBlock);
2985
2986 // Emit code to load the value if it was passed in memory.
2987
2988 CGF.EmitBlock(InMemBlock);
2989 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2990
2991 // Return the appropriate result.
2992
2993 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002994 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002995 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002996 ResAddr->addIncoming(RegAddr, InRegBlock);
2997 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002998 return ResAddr;
2999}
3000
Reid Kleckner80944df2014-10-31 22:00:51 +00003001ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3002 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003003
3004 if (Ty->isVoidType())
3005 return ABIArgInfo::getIgnore();
3006
3007 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3008 Ty = EnumTy->getDecl()->getIntegerType();
3009
Reid Kleckner80944df2014-10-31 22:00:51 +00003010 TypeInfo Info = getContext().getTypeInfo(Ty);
3011 uint64_t Width = Info.Width;
3012 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003013
Reid Kleckner9005f412014-05-02 00:51:20 +00003014 const RecordType *RT = Ty->getAs<RecordType>();
3015 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003016 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003017 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003018 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3019 }
3020
3021 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003022 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3023
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003024 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003025 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003026 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003027 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003028 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003029
Reid Kleckner80944df2014-10-31 22:00:51 +00003030 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3031 // other targets.
3032 const Type *Base = nullptr;
3033 uint64_t NumElts = 0;
3034 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3035 if (FreeSSERegs >= NumElts) {
3036 FreeSSERegs -= NumElts;
3037 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3038 return ABIArgInfo::getDirect();
3039 return ABIArgInfo::getExpand();
3040 }
3041 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3042 }
3043
3044
Reid Klecknerec87fec2014-05-02 01:17:12 +00003045 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003046 // If the member pointer is represented by an LLVM int or ptr, pass it
3047 // directly.
3048 llvm::Type *LLTy = CGT.ConvertType(Ty);
3049 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3050 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003051 }
3052
Michael Kuperstein4f818702015-02-24 09:35:58 +00003053 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003054 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3055 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003056 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003057 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003058
Reid Kleckner9005f412014-05-02 00:51:20 +00003059 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003060 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003061 }
3062
Julien Lerouge10dcff82014-08-27 00:36:55 +00003063 // Bool type is always extended to the ABI, other builtin types are not
3064 // extended.
3065 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3066 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003067 return ABIArgInfo::getExtend();
3068
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003069 return ABIArgInfo::getDirect();
3070}
3071
3072void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003073 bool IsVectorCall =
3074 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003075
Reid Kleckner80944df2014-10-31 22:00:51 +00003076 // We can use up to 4 SSE return registers with vectorcall.
3077 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3078 if (!getCXXABI().classifyReturnType(FI))
3079 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3080
3081 // We can use up to 6 SSE register parameters with vectorcall.
3082 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003083 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003084 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003085}
3086
Chris Lattner04dc9572010-08-31 16:44:54 +00003087llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3088 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003089 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003090
Chris Lattner04dc9572010-08-31 16:44:54 +00003091 CGBuilderTy &Builder = CGF.Builder;
3092 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3093 "ap");
3094 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3095 llvm::Type *PTy =
3096 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3097 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3098
3099 uint64_t Offset =
3100 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3101 llvm::Value *NextAddr =
3102 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3103 "ap.next");
3104 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3105
3106 return AddrTyped;
3107}
Chris Lattner0cf24192010-06-28 20:05:43 +00003108
John McCallea8d8bb2010-03-11 00:10:12 +00003109// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003110namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003111/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3112class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003113public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003114 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3115
3116 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3117 CodeGenFunction &CGF) const override;
3118};
3119
3120class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3121public:
3122 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003123
Craig Topper4f12f102014-03-12 06:41:41 +00003124 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003125 // This is recovered from gcc output.
3126 return 1; // r1 is the dedicated stack pointer
3127 }
3128
3129 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003130 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003131
3132 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3133 return 16; // Natural alignment for Altivec vectors.
3134 }
John McCallea8d8bb2010-03-11 00:10:12 +00003135};
3136
3137}
3138
Roman Divacky8a12d842014-11-03 18:32:54 +00003139llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3140 QualType Ty,
3141 CodeGenFunction &CGF) const {
3142 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3143 // TODO: Implement this. For now ignore.
3144 (void)CTy;
3145 return nullptr;
3146 }
3147
3148 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3149 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3150 llvm::Type *CharPtr = CGF.Int8PtrTy;
3151 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3152
3153 CGBuilderTy &Builder = CGF.Builder;
3154 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3155 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3156 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3157 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3158 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3159 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3160 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3161 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3162 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3163 // Align GPR when TY is i64.
3164 if (isI64) {
3165 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3166 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3167 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3168 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3169 }
3170 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3171 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3172 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3173 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3174 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3175
3176 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3177 Builder.getInt8(8), "cond");
3178
3179 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3180 Builder.getInt8(isInt ? 4 : 8));
3181
3182 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3183
3184 if (Ty->isFloatingType())
3185 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3186
3187 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3188 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3189 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3190
3191 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3192
3193 CGF.EmitBlock(UsingRegs);
3194
3195 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3196 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3197 // Increase the GPR/FPR indexes.
3198 if (isInt) {
3199 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3200 Builder.CreateStore(GPR, GPRPtr);
3201 } else {
3202 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3203 Builder.CreateStore(FPR, FPRPtr);
3204 }
3205 CGF.EmitBranch(Cont);
3206
3207 CGF.EmitBlock(UsingOverflow);
3208
3209 // Increase the overflow area.
3210 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3211 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3212 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3213 CGF.EmitBranch(Cont);
3214
3215 CGF.EmitBlock(Cont);
3216
3217 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3218 Result->addIncoming(Result1, UsingRegs);
3219 Result->addIncoming(Result2, UsingOverflow);
3220
3221 if (Ty->isAggregateType()) {
3222 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3223 return Builder.CreateLoad(AGGPtr, false, "aggr");
3224 }
3225
3226 return Result;
3227}
3228
John McCallea8d8bb2010-03-11 00:10:12 +00003229bool
3230PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3231 llvm::Value *Address) const {
3232 // This is calculated from the LLVM and GCC tables and verified
3233 // against gcc output. AFAIK all ABIs use the same encoding.
3234
3235 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003236
Chris Lattnerece04092012-02-07 00:39:47 +00003237 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003238 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3239 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3240 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3241
3242 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003243 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003244
3245 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003246 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003247
3248 // 64-76 are various 4-byte special-purpose registers:
3249 // 64: mq
3250 // 65: lr
3251 // 66: ctr
3252 // 67: ap
3253 // 68-75 cr0-7
3254 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003255 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003256
3257 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003258 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003259
3260 // 109: vrsave
3261 // 110: vscr
3262 // 111: spe_acc
3263 // 112: spefscr
3264 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003265 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003266
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003267 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003268}
3269
Roman Divackyd966e722012-05-09 18:22:46 +00003270// PowerPC-64
3271
3272namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003273/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3274class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003275public:
3276 enum ABIKind {
3277 ELFv1 = 0,
3278 ELFv2
3279 };
3280
3281private:
3282 static const unsigned GPRBits = 64;
3283 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003284 bool HasQPX;
3285
3286 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3287 // will be passed in a QPX register.
3288 bool IsQPXVectorTy(const Type *Ty) const {
3289 if (!HasQPX)
3290 return false;
3291
3292 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3293 unsigned NumElements = VT->getNumElements();
3294 if (NumElements == 1)
3295 return false;
3296
3297 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3298 if (getContext().getTypeSize(Ty) <= 256)
3299 return true;
3300 } else if (VT->getElementType()->
3301 isSpecificBuiltinType(BuiltinType::Float)) {
3302 if (getContext().getTypeSize(Ty) <= 128)
3303 return true;
3304 }
3305 }
3306
3307 return false;
3308 }
3309
3310 bool IsQPXVectorTy(QualType Ty) const {
3311 return IsQPXVectorTy(Ty.getTypePtr());
3312 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003313
3314public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003315 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3316 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003317
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003318 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003319 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003320
3321 ABIArgInfo classifyReturnType(QualType RetTy) const;
3322 ABIArgInfo classifyArgumentType(QualType Ty) const;
3323
Reid Klecknere9f6a712014-10-31 17:10:41 +00003324 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3325 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3326 uint64_t Members) const override;
3327
Bill Schmidt84d37792012-10-12 19:26:17 +00003328 // TODO: We can add more logic to computeInfo to improve performance.
3329 // Example: For aggregate arguments that fit in a register, we could
3330 // use getDirectInReg (as is done below for structs containing a single
3331 // floating-point value) to avoid pushing them to memory on function
3332 // entry. This would require changing the logic in PPCISelLowering
3333 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003334 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003335 if (!getCXXABI().classifyReturnType(FI))
3336 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003337 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003338 // We rely on the default argument classification for the most part.
3339 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003340 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003341 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003342 if (T) {
3343 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003344 if (IsQPXVectorTy(T) ||
3345 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003346 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003347 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003348 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003349 continue;
3350 }
3351 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003352 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003353 }
3354 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003355
Craig Topper4f12f102014-03-12 06:41:41 +00003356 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3357 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003358};
3359
3360class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003361 bool HasQPX;
3362
Bill Schmidt25cb3492012-10-03 19:18:57 +00003363public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003364 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003365 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
3366 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)),
3367 HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003368
Craig Topper4f12f102014-03-12 06:41:41 +00003369 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003370 // This is recovered from gcc output.
3371 return 1; // r1 is the dedicated stack pointer
3372 }
3373
3374 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003375 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003376
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003377 unsigned getOpenMPSimdDefaultAlignment(QualType QT) const override {
3378 if (HasQPX)
3379 if (const PointerType *PT = QT->getAs<PointerType>())
3380 if (PT->getPointeeType()->isSpecificBuiltinType(BuiltinType::Double))
3381 return 32; // Natural alignment for QPX doubles.
3382
Hal Finkel92e31a52014-10-03 17:45:20 +00003383 return 16; // Natural alignment for Altivec and VSX vectors.
3384 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003385};
3386
Roman Divackyd966e722012-05-09 18:22:46 +00003387class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3388public:
3389 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3390
Craig Topper4f12f102014-03-12 06:41:41 +00003391 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003392 // This is recovered from gcc output.
3393 return 1; // r1 is the dedicated stack pointer
3394 }
3395
3396 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003397 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003398
3399 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3400 return 16; // Natural alignment for Altivec vectors.
3401 }
Roman Divackyd966e722012-05-09 18:22:46 +00003402};
3403
3404}
3405
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003406// Return true if the ABI requires Ty to be passed sign- or zero-
3407// extended to 64 bits.
3408bool
3409PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3410 // Treat an enum type as its underlying type.
3411 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3412 Ty = EnumTy->getDecl()->getIntegerType();
3413
3414 // Promotable integer types are required to be promoted by the ABI.
3415 if (Ty->isPromotableIntegerType())
3416 return true;
3417
3418 // In addition to the usual promotable integer types, we also need to
3419 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3420 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3421 switch (BT->getKind()) {
3422 case BuiltinType::Int:
3423 case BuiltinType::UInt:
3424 return true;
3425 default:
3426 break;
3427 }
3428
3429 return false;
3430}
3431
Ulrich Weigand581badc2014-07-10 17:20:07 +00003432/// isAlignedParamType - Determine whether a type requires 16-byte
3433/// alignment in the parameter area.
3434bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003435PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3436 Align32 = false;
3437
Ulrich Weigand581badc2014-07-10 17:20:07 +00003438 // Complex types are passed just like their elements.
3439 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3440 Ty = CTy->getElementType();
3441
3442 // Only vector types of size 16 bytes need alignment (larger types are
3443 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003444 if (IsQPXVectorTy(Ty)) {
3445 if (getContext().getTypeSize(Ty) > 128)
3446 Align32 = true;
3447
3448 return true;
3449 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003450 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003451 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003452
3453 // For single-element float/vector structs, we consider the whole type
3454 // to have the same alignment requirements as its single element.
3455 const Type *AlignAsType = nullptr;
3456 const Type *EltType = isSingleElementStruct(Ty, getContext());
3457 if (EltType) {
3458 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003459 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003460 getContext().getTypeSize(EltType) == 128) ||
3461 (BT && BT->isFloatingPoint()))
3462 AlignAsType = EltType;
3463 }
3464
Ulrich Weigandb7122372014-07-21 00:48:09 +00003465 // Likewise for ELFv2 homogeneous aggregates.
3466 const Type *Base = nullptr;
3467 uint64_t Members = 0;
3468 if (!AlignAsType && Kind == ELFv2 &&
3469 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3470 AlignAsType = Base;
3471
Ulrich Weigand581badc2014-07-10 17:20:07 +00003472 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003473 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3474 if (getContext().getTypeSize(AlignAsType) > 128)
3475 Align32 = true;
3476
3477 return true;
3478 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003479 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003480 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003481
3482 // Otherwise, we only need alignment for any aggregate type that
3483 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003484 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3485 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3486 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003487 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003488 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003489
3490 return false;
3491}
3492
Ulrich Weigandb7122372014-07-21 00:48:09 +00003493/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3494/// aggregate. Base is set to the base element type, and Members is set
3495/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003496bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3497 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003498 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3499 uint64_t NElements = AT->getSize().getZExtValue();
3500 if (NElements == 0)
3501 return false;
3502 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3503 return false;
3504 Members *= NElements;
3505 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3506 const RecordDecl *RD = RT->getDecl();
3507 if (RD->hasFlexibleArrayMember())
3508 return false;
3509
3510 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003511
3512 // If this is a C++ record, check the bases first.
3513 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3514 for (const auto &I : CXXRD->bases()) {
3515 // Ignore empty records.
3516 if (isEmptyRecord(getContext(), I.getType(), true))
3517 continue;
3518
3519 uint64_t FldMembers;
3520 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3521 return false;
3522
3523 Members += FldMembers;
3524 }
3525 }
3526
Ulrich Weigandb7122372014-07-21 00:48:09 +00003527 for (const auto *FD : RD->fields()) {
3528 // Ignore (non-zero arrays of) empty records.
3529 QualType FT = FD->getType();
3530 while (const ConstantArrayType *AT =
3531 getContext().getAsConstantArrayType(FT)) {
3532 if (AT->getSize().getZExtValue() == 0)
3533 return false;
3534 FT = AT->getElementType();
3535 }
3536 if (isEmptyRecord(getContext(), FT, true))
3537 continue;
3538
3539 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3540 if (getContext().getLangOpts().CPlusPlus &&
3541 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3542 continue;
3543
3544 uint64_t FldMembers;
3545 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3546 return false;
3547
3548 Members = (RD->isUnion() ?
3549 std::max(Members, FldMembers) : Members + FldMembers);
3550 }
3551
3552 if (!Base)
3553 return false;
3554
3555 // Ensure there is no padding.
3556 if (getContext().getTypeSize(Base) * Members !=
3557 getContext().getTypeSize(Ty))
3558 return false;
3559 } else {
3560 Members = 1;
3561 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3562 Members = 2;
3563 Ty = CT->getElementType();
3564 }
3565
Reid Klecknere9f6a712014-10-31 17:10:41 +00003566 // Most ABIs only support float, double, and some vector type widths.
3567 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003568 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003569
3570 // The base type must be the same for all members. Types that
3571 // agree in both total size and mode (float vs. vector) are
3572 // treated as being equivalent here.
3573 const Type *TyPtr = Ty.getTypePtr();
3574 if (!Base)
3575 Base = TyPtr;
3576
3577 if (Base->isVectorType() != TyPtr->isVectorType() ||
3578 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3579 return false;
3580 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003581 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3582}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003583
Reid Klecknere9f6a712014-10-31 17:10:41 +00003584bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3585 // Homogeneous aggregates for ELFv2 must have base types of float,
3586 // double, long double, or 128-bit vectors.
3587 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3588 if (BT->getKind() == BuiltinType::Float ||
3589 BT->getKind() == BuiltinType::Double ||
3590 BT->getKind() == BuiltinType::LongDouble)
3591 return true;
3592 }
3593 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003594 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003595 return true;
3596 }
3597 return false;
3598}
3599
3600bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3601 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003602 // Vector types require one register, floating point types require one
3603 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003604 uint32_t NumRegs =
3605 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003606
3607 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003608 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003609}
3610
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003611ABIArgInfo
3612PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003613 Ty = useFirstFieldIfTransparentUnion(Ty);
3614
Bill Schmidt90b22c92012-11-27 02:46:43 +00003615 if (Ty->isAnyComplexType())
3616 return ABIArgInfo::getDirect();
3617
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003618 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3619 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003620 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003621 uint64_t Size = getContext().getTypeSize(Ty);
3622 if (Size > 128)
3623 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3624 else if (Size < 128) {
3625 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3626 return ABIArgInfo::getDirect(CoerceTy);
3627 }
3628 }
3629
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003630 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003631 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003632 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003633
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003634 bool Align32;
3635 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3636 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003637 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003638
3639 // ELFv2 homogeneous aggregates are passed as array types.
3640 const Type *Base = nullptr;
3641 uint64_t Members = 0;
3642 if (Kind == ELFv2 &&
3643 isHomogeneousAggregate(Ty, Base, Members)) {
3644 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3645 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3646 return ABIArgInfo::getDirect(CoerceTy);
3647 }
3648
Ulrich Weigand601957f2014-07-21 00:56:36 +00003649 // If an aggregate may end up fully in registers, we do not
3650 // use the ByVal method, but pass the aggregate as array.
3651 // This is usually beneficial since we avoid forcing the
3652 // back-end to store the argument to memory.
3653 uint64_t Bits = getContext().getTypeSize(Ty);
3654 if (Bits > 0 && Bits <= 8 * GPRBits) {
3655 llvm::Type *CoerceTy;
3656
3657 // Types up to 8 bytes are passed as integer type (which will be
3658 // properly aligned in the argument save area doubleword).
3659 if (Bits <= GPRBits)
3660 CoerceTy = llvm::IntegerType::get(getVMContext(),
3661 llvm::RoundUpToAlignment(Bits, 8));
3662 // Larger types are passed as arrays, with the base type selected
3663 // according to the required alignment in the save area.
3664 else {
3665 uint64_t RegBits = ABIAlign * 8;
3666 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3667 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3668 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3669 }
3670
3671 return ABIArgInfo::getDirect(CoerceTy);
3672 }
3673
Ulrich Weigandb7122372014-07-21 00:48:09 +00003674 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003675 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3676 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003677 }
3678
3679 return (isPromotableTypeForABI(Ty) ?
3680 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3681}
3682
3683ABIArgInfo
3684PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3685 if (RetTy->isVoidType())
3686 return ABIArgInfo::getIgnore();
3687
Bill Schmidta3d121c2012-12-17 04:20:17 +00003688 if (RetTy->isAnyComplexType())
3689 return ABIArgInfo::getDirect();
3690
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003691 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3692 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003693 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003694 uint64_t Size = getContext().getTypeSize(RetTy);
3695 if (Size > 128)
3696 return ABIArgInfo::getIndirect(0);
3697 else if (Size < 128) {
3698 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3699 return ABIArgInfo::getDirect(CoerceTy);
3700 }
3701 }
3702
Ulrich Weigandb7122372014-07-21 00:48:09 +00003703 if (isAggregateTypeForABI(RetTy)) {
3704 // ELFv2 homogeneous aggregates are returned as array types.
3705 const Type *Base = nullptr;
3706 uint64_t Members = 0;
3707 if (Kind == ELFv2 &&
3708 isHomogeneousAggregate(RetTy, Base, Members)) {
3709 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3710 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3711 return ABIArgInfo::getDirect(CoerceTy);
3712 }
3713
3714 // ELFv2 small aggregates are returned in up to two registers.
3715 uint64_t Bits = getContext().getTypeSize(RetTy);
3716 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3717 if (Bits == 0)
3718 return ABIArgInfo::getIgnore();
3719
3720 llvm::Type *CoerceTy;
3721 if (Bits > GPRBits) {
3722 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003723 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003724 } else
3725 CoerceTy = llvm::IntegerType::get(getVMContext(),
3726 llvm::RoundUpToAlignment(Bits, 8));
3727 return ABIArgInfo::getDirect(CoerceTy);
3728 }
3729
3730 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003731 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003732 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003733
3734 return (isPromotableTypeForABI(RetTy) ?
3735 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3736}
3737
Bill Schmidt25cb3492012-10-03 19:18:57 +00003738// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3739llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3740 QualType Ty,
3741 CodeGenFunction &CGF) const {
3742 llvm::Type *BP = CGF.Int8PtrTy;
3743 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3744
3745 CGBuilderTy &Builder = CGF.Builder;
3746 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3747 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3748
Ulrich Weigand581badc2014-07-10 17:20:07 +00003749 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003750 bool Align32;
3751 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003752 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003753 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3754 Builder.getInt64(Align32 ? 31 : 15));
3755 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3756 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003757 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3758 }
3759
Bill Schmidt924c4782013-01-14 17:45:36 +00003760 // Update the va_list pointer. The pointer should be bumped by the
3761 // size of the object. We can trust getTypeSize() except for a complex
3762 // type whose base type is smaller than a doubleword. For these, the
3763 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003764 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003765 QualType BaseTy;
3766 unsigned CplxBaseSize = 0;
3767
3768 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3769 BaseTy = CTy->getElementType();
3770 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3771 if (CplxBaseSize < 8)
3772 SizeInBytes = 16;
3773 }
3774
Bill Schmidt25cb3492012-10-03 19:18:57 +00003775 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3776 llvm::Value *NextAddr =
3777 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3778 "ap.next");
3779 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3780
Bill Schmidt924c4782013-01-14 17:45:36 +00003781 // If we have a complex type and the base type is smaller than 8 bytes,
3782 // the ABI calls for the real and imaginary parts to be right-adjusted
3783 // in separate doublewords. However, Clang expects us to produce a
3784 // pointer to a structure with the two parts packed tightly. So generate
3785 // loads of the real and imaginary parts relative to the va_list pointer,
3786 // and store them to a temporary structure.
3787 if (CplxBaseSize && CplxBaseSize < 8) {
3788 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3789 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003790 if (CGF.CGM.getDataLayout().isBigEndian()) {
3791 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3792 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3793 } else {
3794 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3795 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003796 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3797 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3798 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3799 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3800 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003801 llvm::AllocaInst *Ptr =
3802 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3803 llvm::Value *RealPtr =
3804 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3805 llvm::Value *ImagPtr =
3806 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003807 Builder.CreateStore(Real, RealPtr, false);
3808 Builder.CreateStore(Imag, ImagPtr, false);
3809 return Ptr;
3810 }
3811
Bill Schmidt25cb3492012-10-03 19:18:57 +00003812 // If the argument is smaller than 8 bytes, it is right-adjusted in
3813 // its doubleword slot. Adjust the pointer to pick it up from the
3814 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003815 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003816 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3817 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3818 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3819 }
3820
3821 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3822 return Builder.CreateBitCast(Addr, PTy);
3823}
3824
3825static bool
3826PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3827 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003828 // This is calculated from the LLVM and GCC tables and verified
3829 // against gcc output. AFAIK all ABIs use the same encoding.
3830
3831 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3832
3833 llvm::IntegerType *i8 = CGF.Int8Ty;
3834 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3835 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3836 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3837
3838 // 0-31: r0-31, the 8-byte general-purpose registers
3839 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3840
3841 // 32-63: fp0-31, the 8-byte floating-point registers
3842 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3843
3844 // 64-76 are various 4-byte special-purpose registers:
3845 // 64: mq
3846 // 65: lr
3847 // 66: ctr
3848 // 67: ap
3849 // 68-75 cr0-7
3850 // 76: xer
3851 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3852
3853 // 77-108: v0-31, the 16-byte vector registers
3854 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3855
3856 // 109: vrsave
3857 // 110: vscr
3858 // 111: spe_acc
3859 // 112: spefscr
3860 // 113: sfp
3861 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3862
3863 return false;
3864}
John McCallea8d8bb2010-03-11 00:10:12 +00003865
Bill Schmidt25cb3492012-10-03 19:18:57 +00003866bool
3867PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3868 CodeGen::CodeGenFunction &CGF,
3869 llvm::Value *Address) const {
3870
3871 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3872}
3873
3874bool
3875PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3876 llvm::Value *Address) const {
3877
3878 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3879}
3880
Chris Lattner0cf24192010-06-28 20:05:43 +00003881//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003882// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003883//===----------------------------------------------------------------------===//
3884
3885namespace {
3886
Tim Northover573cbee2014-05-24 12:52:07 +00003887class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003888public:
3889 enum ABIKind {
3890 AAPCS = 0,
3891 DarwinPCS
3892 };
3893
3894private:
3895 ABIKind Kind;
3896
3897public:
Tim Northover573cbee2014-05-24 12:52:07 +00003898 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003899
3900private:
3901 ABIKind getABIKind() const { return Kind; }
3902 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3903
3904 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003905 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003906 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3907 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3908 uint64_t Members) const override;
3909
Tim Northovera2ee4332014-03-29 15:09:45 +00003910 bool isIllegalVectorType(QualType Ty) const;
3911
David Blaikie1cbb9712014-11-14 19:09:44 +00003912 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003913 if (!getCXXABI().classifyReturnType(FI))
3914 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003915
Tim Northoverb047bfa2014-11-27 21:02:49 +00003916 for (auto &it : FI.arguments())
3917 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003918 }
3919
3920 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3921 CodeGenFunction &CGF) const;
3922
3923 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3924 CodeGenFunction &CGF) const;
3925
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003926 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3927 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003928 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3929 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3930 }
3931};
3932
Tim Northover573cbee2014-05-24 12:52:07 +00003933class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003934public:
Tim Northover573cbee2014-05-24 12:52:07 +00003935 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3936 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003937
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003938 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003939 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3940 }
3941
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003942 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3943 return 31;
3944 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003945
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003946 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00003947};
3948}
3949
Tim Northoverb047bfa2014-11-27 21:02:49 +00003950ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003951 Ty = useFirstFieldIfTransparentUnion(Ty);
3952
Tim Northovera2ee4332014-03-29 15:09:45 +00003953 // Handle illegal vector types here.
3954 if (isIllegalVectorType(Ty)) {
3955 uint64_t Size = getContext().getTypeSize(Ty);
3956 if (Size <= 32) {
3957 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003958 return ABIArgInfo::getDirect(ResType);
3959 }
3960 if (Size == 64) {
3961 llvm::Type *ResType =
3962 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003963 return ABIArgInfo::getDirect(ResType);
3964 }
3965 if (Size == 128) {
3966 llvm::Type *ResType =
3967 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003968 return ABIArgInfo::getDirect(ResType);
3969 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003970 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3971 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003972
3973 if (!isAggregateTypeForABI(Ty)) {
3974 // Treat an enum type as its underlying type.
3975 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3976 Ty = EnumTy->getDecl()->getIntegerType();
3977
Tim Northovera2ee4332014-03-29 15:09:45 +00003978 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3979 ? ABIArgInfo::getExtend()
3980 : ABIArgInfo::getDirect());
3981 }
3982
3983 // Structures with either a non-trivial destructor or a non-trivial
3984 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003985 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003986 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003987 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003988 }
3989
3990 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3991 // elsewhere for GNU compatibility.
3992 if (isEmptyRecord(getContext(), Ty, true)) {
3993 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3994 return ABIArgInfo::getIgnore();
3995
Tim Northovera2ee4332014-03-29 15:09:45 +00003996 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3997 }
3998
3999 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004000 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004001 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004002 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004003 return ABIArgInfo::getDirect(
4004 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004005 }
4006
4007 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4008 uint64_t Size = getContext().getTypeSize(Ty);
4009 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004010 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004011 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004012
Tim Northovera2ee4332014-03-29 15:09:45 +00004013 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4014 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004015 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004016 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4017 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4018 }
4019 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4020 }
4021
Tim Northovera2ee4332014-03-29 15:09:45 +00004022 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4023}
4024
Tim Northover573cbee2014-05-24 12:52:07 +00004025ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004026 if (RetTy->isVoidType())
4027 return ABIArgInfo::getIgnore();
4028
4029 // Large vector types should be returned via memory.
4030 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4031 return ABIArgInfo::getIndirect(0);
4032
4033 if (!isAggregateTypeForABI(RetTy)) {
4034 // Treat an enum type as its underlying type.
4035 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4036 RetTy = EnumTy->getDecl()->getIntegerType();
4037
Tim Northover4dab6982014-04-18 13:46:08 +00004038 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4039 ? ABIArgInfo::getExtend()
4040 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004041 }
4042
Tim Northovera2ee4332014-03-29 15:09:45 +00004043 if (isEmptyRecord(getContext(), RetTy, true))
4044 return ABIArgInfo::getIgnore();
4045
Craig Topper8a13c412014-05-21 05:09:00 +00004046 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004047 uint64_t Members = 0;
4048 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004049 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4050 return ABIArgInfo::getDirect();
4051
4052 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4053 uint64_t Size = getContext().getTypeSize(RetTy);
4054 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004055 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004056 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004057
4058 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4059 // For aggregates with 16-byte alignment, we use i128.
4060 if (Alignment < 128 && Size == 128) {
4061 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4062 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4063 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004064 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4065 }
4066
4067 return ABIArgInfo::getIndirect(0);
4068}
4069
Tim Northover573cbee2014-05-24 12:52:07 +00004070/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4071bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004072 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4073 // Check whether VT is legal.
4074 unsigned NumElements = VT->getNumElements();
4075 uint64_t Size = getContext().getTypeSize(VT);
4076 // NumElements should be power of 2 between 1 and 16.
4077 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4078 return true;
4079 return Size != 64 && (Size != 128 || NumElements == 1);
4080 }
4081 return false;
4082}
4083
Reid Klecknere9f6a712014-10-31 17:10:41 +00004084bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4085 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4086 // point type or a short-vector type. This is the same as the 32-bit ABI,
4087 // but with the difference that any floating-point type is allowed,
4088 // including __fp16.
4089 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4090 if (BT->isFloatingPoint())
4091 return true;
4092 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4093 unsigned VecSize = getContext().getTypeSize(VT);
4094 if (VecSize == 64 || VecSize == 128)
4095 return true;
4096 }
4097 return false;
4098}
4099
4100bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4101 uint64_t Members) const {
4102 return Members <= 4;
4103}
4104
Tim Northoverb047bfa2014-11-27 21:02:49 +00004105llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4106 QualType Ty,
4107 CodeGenFunction &CGF) const {
4108 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004109 bool IsIndirect = AI.isIndirect();
4110
Tim Northoverb047bfa2014-11-27 21:02:49 +00004111 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4112 if (IsIndirect)
4113 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4114 else if (AI.getCoerceToType())
4115 BaseTy = AI.getCoerceToType();
4116
4117 unsigned NumRegs = 1;
4118 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4119 BaseTy = ArrTy->getElementType();
4120 NumRegs = ArrTy->getNumElements();
4121 }
4122 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4123
Tim Northovera2ee4332014-03-29 15:09:45 +00004124 // The AArch64 va_list type and handling is specified in the Procedure Call
4125 // Standard, section B.4:
4126 //
4127 // struct {
4128 // void *__stack;
4129 // void *__gr_top;
4130 // void *__vr_top;
4131 // int __gr_offs;
4132 // int __vr_offs;
4133 // };
4134
4135 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4136 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4137 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4138 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4139 auto &Ctx = CGF.getContext();
4140
Craig Topper8a13c412014-05-21 05:09:00 +00004141 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004142 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004143 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4144 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004145 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004146 reg_offs_p =
4147 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004148 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4149 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004150 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004151 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004152 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004153 reg_offs_p =
4154 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004155 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4156 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004157 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004158 }
4159
4160 //=======================================
4161 // Find out where argument was passed
4162 //=======================================
4163
4164 // If reg_offs >= 0 we're already using the stack for this type of
4165 // argument. We don't want to keep updating reg_offs (in case it overflows,
4166 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4167 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004168 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004169 UsingStack = CGF.Builder.CreateICmpSGE(
4170 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4171
4172 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4173
4174 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004175 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004176 CGF.EmitBlock(MaybeRegBlock);
4177
4178 // Integer arguments may need to correct register alignment (for example a
4179 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4180 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004181 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004182 int Align = Ctx.getTypeAlign(Ty) / 8;
4183
4184 reg_offs = CGF.Builder.CreateAdd(
4185 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4186 "align_regoffs");
4187 reg_offs = CGF.Builder.CreateAnd(
4188 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4189 "aligned_regoffs");
4190 }
4191
4192 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004193 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004194 NewOffset = CGF.Builder.CreateAdd(
4195 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4196 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4197
4198 // Now we're in a position to decide whether this argument really was in
4199 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004200 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004201 InRegs = CGF.Builder.CreateICmpSLE(
4202 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4203
4204 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4205
4206 //=======================================
4207 // Argument was in registers
4208 //=======================================
4209
4210 // Now we emit the code for if the argument was originally passed in
4211 // registers. First start the appropriate block:
4212 CGF.EmitBlock(InRegBlock);
4213
Craig Topper8a13c412014-05-21 05:09:00 +00004214 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004215 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4216 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004217 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4218 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004219 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004220 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4221
4222 if (IsIndirect) {
4223 // If it's been passed indirectly (actually a struct), whatever we find from
4224 // stored registers or on the stack will actually be a struct **.
4225 MemTy = llvm::PointerType::getUnqual(MemTy);
4226 }
4227
Craig Topper8a13c412014-05-21 05:09:00 +00004228 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004229 uint64_t NumMembers = 0;
4230 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004231 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004232 // Homogeneous aggregates passed in registers will have their elements split
4233 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4234 // qN+1, ...). We reload and store into a temporary local variable
4235 // contiguously.
4236 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4237 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4238 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004239 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004240 int Offset = 0;
4241
4242 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4243 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4244 for (unsigned i = 0; i < NumMembers; ++i) {
4245 llvm::Value *BaseOffset =
4246 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4247 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4248 LoadAddr = CGF.Builder.CreateBitCast(
4249 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004250 llvm::Value *StoreAddr =
4251 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004252
4253 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4254 CGF.Builder.CreateStore(Elem, StoreAddr);
4255 }
4256
4257 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4258 } else {
4259 // Otherwise the object is contiguous in memory
4260 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004261 if (CGF.CGM.getDataLayout().isBigEndian() &&
4262 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004263 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4264 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4265 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4266
4267 BaseAddr = CGF.Builder.CreateAdd(
4268 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4269
4270 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4271 }
4272
4273 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4274 }
4275
4276 CGF.EmitBranch(ContBlock);
4277
4278 //=======================================
4279 // Argument was on the stack
4280 //=======================================
4281 CGF.EmitBlock(OnStackBlock);
4282
Craig Topper8a13c412014-05-21 05:09:00 +00004283 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004284 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004285 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4286
4287 // Again, stack arguments may need realigmnent. In this case both integer and
4288 // floating-point ones might be affected.
4289 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4290 int Align = Ctx.getTypeAlign(Ty) / 8;
4291
4292 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4293
4294 OnStackAddr = CGF.Builder.CreateAdd(
4295 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4296 "align_stack");
4297 OnStackAddr = CGF.Builder.CreateAnd(
4298 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4299 "align_stack");
4300
4301 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4302 }
4303
4304 uint64_t StackSize;
4305 if (IsIndirect)
4306 StackSize = 8;
4307 else
4308 StackSize = Ctx.getTypeSize(Ty) / 8;
4309
4310 // All stack slots are 8 bytes
4311 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4312
4313 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4314 llvm::Value *NewStack =
4315 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4316
4317 // Write the new value of __stack for the next call to va_arg
4318 CGF.Builder.CreateStore(NewStack, stack_p);
4319
4320 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4321 Ctx.getTypeSize(Ty) < 64) {
4322 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4323 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4324
4325 OnStackAddr = CGF.Builder.CreateAdd(
4326 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4327
4328 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4329 }
4330
4331 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4332
4333 CGF.EmitBranch(ContBlock);
4334
4335 //=======================================
4336 // Tidy up
4337 //=======================================
4338 CGF.EmitBlock(ContBlock);
4339
4340 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4341 ResAddr->addIncoming(RegAddr, InRegBlock);
4342 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4343
4344 if (IsIndirect)
4345 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4346
4347 return ResAddr;
4348}
4349
Tim Northover573cbee2014-05-24 12:52:07 +00004350llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004351 CodeGenFunction &CGF) const {
4352 // We do not support va_arg for aggregates or illegal vector types.
4353 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4354 // other cases.
4355 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004356 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004357
4358 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4359 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4360
Craig Topper8a13c412014-05-21 05:09:00 +00004361 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004362 uint64_t Members = 0;
4363 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004364
4365 bool isIndirect = false;
4366 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4367 // be passed indirectly.
4368 if (Size > 16 && !isHA) {
4369 isIndirect = true;
4370 Size = 8;
4371 Align = 8;
4372 }
4373
4374 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4375 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4376
4377 CGBuilderTy &Builder = CGF.Builder;
4378 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4379 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4380
4381 if (isEmptyRecord(getContext(), Ty, true)) {
4382 // These are ignored for parameter passing purposes.
4383 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4384 return Builder.CreateBitCast(Addr, PTy);
4385 }
4386
4387 const uint64_t MinABIAlign = 8;
4388 if (Align > MinABIAlign) {
4389 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4390 Addr = Builder.CreateGEP(Addr, Offset);
4391 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4392 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4393 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4394 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4395 }
4396
4397 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4398 llvm::Value *NextAddr = Builder.CreateGEP(
4399 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4400 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4401
4402 if (isIndirect)
4403 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4404 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4405 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4406
4407 return AddrTyped;
4408}
4409
4410//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004411// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004412//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004413
4414namespace {
4415
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004416class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004417public:
4418 enum ABIKind {
4419 APCS = 0,
4420 AAPCS = 1,
4421 AAPCS_VFP
4422 };
4423
4424private:
4425 ABIKind Kind;
4426
4427public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004428 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004429 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004430 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004431
John McCall3480ef22011-08-30 01:42:09 +00004432 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004433 switch (getTarget().getTriple().getEnvironment()) {
4434 case llvm::Triple::Android:
4435 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004436 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004437 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004438 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004439 return true;
4440 default:
4441 return false;
4442 }
John McCall3480ef22011-08-30 01:42:09 +00004443 }
4444
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004445 bool isEABIHF() const {
4446 switch (getTarget().getTriple().getEnvironment()) {
4447 case llvm::Triple::EABIHF:
4448 case llvm::Triple::GNUEABIHF:
4449 return true;
4450 default:
4451 return false;
4452 }
4453 }
4454
Daniel Dunbar020daa92009-09-12 01:00:39 +00004455 ABIKind getABIKind() const { return Kind; }
4456
Tim Northovera484bc02013-10-01 14:34:25 +00004457private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004458 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004459 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004460 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004461
Reid Klecknere9f6a712014-10-31 17:10:41 +00004462 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4463 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4464 uint64_t Members) const override;
4465
Craig Topper4f12f102014-03-12 06:41:41 +00004466 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004467
Craig Topper4f12f102014-03-12 06:41:41 +00004468 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4469 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004470
4471 llvm::CallingConv::ID getLLVMDefaultCC() const;
4472 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004473 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004474};
4475
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004476class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4477public:
Chris Lattner2b037972010-07-29 02:01:43 +00004478 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4479 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004480
John McCall3480ef22011-08-30 01:42:09 +00004481 const ARMABIInfo &getABIInfo() const {
4482 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4483 }
4484
Craig Topper4f12f102014-03-12 06:41:41 +00004485 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004486 return 13;
4487 }
Roman Divackyc1617352011-05-18 19:36:54 +00004488
Craig Topper4f12f102014-03-12 06:41:41 +00004489 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004490 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4491 }
4492
Roman Divackyc1617352011-05-18 19:36:54 +00004493 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004494 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004495 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004496
4497 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004498 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004499 return false;
4500 }
John McCall3480ef22011-08-30 01:42:09 +00004501
Craig Topper4f12f102014-03-12 06:41:41 +00004502 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004503 if (getABIInfo().isEABI()) return 88;
4504 return TargetCodeGenInfo::getSizeOfUnwindException();
4505 }
Tim Northovera484bc02013-10-01 14:34:25 +00004506
4507 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004508 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004509 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4510 if (!FD)
4511 return;
4512
4513 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4514 if (!Attr)
4515 return;
4516
4517 const char *Kind;
4518 switch (Attr->getInterrupt()) {
4519 case ARMInterruptAttr::Generic: Kind = ""; break;
4520 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4521 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4522 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4523 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4524 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4525 }
4526
4527 llvm::Function *Fn = cast<llvm::Function>(GV);
4528
4529 Fn->addFnAttr("interrupt", Kind);
4530
4531 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4532 return;
4533
4534 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4535 // however this is not necessarily true on taking any interrupt. Instruct
4536 // the backend to perform a realignment as part of the function prologue.
4537 llvm::AttrBuilder B;
4538 B.addStackAlignmentAttr(8);
4539 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4540 llvm::AttributeSet::get(CGM.getLLVMContext(),
4541 llvm::AttributeSet::FunctionIndex,
4542 B));
4543 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004544};
4545
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004546class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4547 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4548 CodeGen::CodeGenModule &CGM) const;
4549
4550public:
4551 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4552 : ARMTargetCodeGenInfo(CGT, K) {}
4553
4554 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4555 CodeGen::CodeGenModule &CGM) const override;
4556};
4557
4558void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4559 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4560 if (!isa<FunctionDecl>(D))
4561 return;
4562 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4563 return;
4564
4565 llvm::Function *F = cast<llvm::Function>(GV);
4566 F->addFnAttr("stack-probe-size",
4567 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4568}
4569
4570void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4571 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4572 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4573 addStackProbeSizeTargetAttribute(D, GV, CGM);
4574}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004575}
4576
Chris Lattner22326a12010-07-29 02:31:05 +00004577void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004578 if (!getCXXABI().classifyReturnType(FI))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004579 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004580
Tim Northoverbc784d12015-02-24 17:22:40 +00004581 for (auto &I : FI.arguments())
4582 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004583
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004584 // Always honor user-specified calling convention.
4585 if (FI.getCallingConvention() != llvm::CallingConv::C)
4586 return;
4587
John McCall882987f2013-02-28 19:01:20 +00004588 llvm::CallingConv::ID cc = getRuntimeCC();
4589 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004590 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004591}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004592
John McCall882987f2013-02-28 19:01:20 +00004593/// Return the default calling convention that LLVM will use.
4594llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4595 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004596 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004597 return llvm::CallingConv::ARM_AAPCS_VFP;
4598 else if (isEABI())
4599 return llvm::CallingConv::ARM_AAPCS;
4600 else
4601 return llvm::CallingConv::ARM_APCS;
4602}
4603
4604/// Return the calling convention that our ABI would like us to use
4605/// as the C calling convention.
4606llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004607 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004608 case APCS: return llvm::CallingConv::ARM_APCS;
4609 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4610 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004611 }
John McCall882987f2013-02-28 19:01:20 +00004612 llvm_unreachable("bad ABI kind");
4613}
4614
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004615void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004616 assert(getRuntimeCC() == llvm::CallingConv::C);
4617
4618 // Don't muddy up the IR with a ton of explicit annotations if
4619 // they'd just match what LLVM will infer from the triple.
4620 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4621 if (abiCC != getLLVMDefaultCC())
4622 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004623
4624 BuiltinCC = (getABIKind() == APCS ?
4625 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004626}
4627
Tim Northoverbc784d12015-02-24 17:22:40 +00004628ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4629 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004630 // 6.1.2.1 The following argument types are VFP CPRCs:
4631 // A single-precision floating-point type (including promoted
4632 // half-precision types); A double-precision floating-point type;
4633 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4634 // with a Base Type of a single- or double-precision floating-point type,
4635 // 64-bit containerized vectors or 128-bit containerized vectors with one
4636 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004637 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004638
Reid Klecknerb1be6832014-11-15 01:41:41 +00004639 Ty = useFirstFieldIfTransparentUnion(Ty);
4640
Manman Renfef9e312012-10-16 19:18:39 +00004641 // Handle illegal vector types here.
4642 if (isIllegalVectorType(Ty)) {
4643 uint64_t Size = getContext().getTypeSize(Ty);
4644 if (Size <= 32) {
4645 llvm::Type *ResType =
4646 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004647 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004648 }
4649 if (Size == 64) {
4650 llvm::Type *ResType = llvm::VectorType::get(
4651 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004652 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004653 }
4654 if (Size == 128) {
4655 llvm::Type *ResType = llvm::VectorType::get(
4656 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004657 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004658 }
4659 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4660 }
4661
John McCalla1dee5302010-08-22 10:59:02 +00004662 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004663 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004664 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004665 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004666 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004667
Tim Northover5a1558e2014-11-07 22:30:50 +00004668 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4669 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004670 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004671
Oliver Stannard405bded2014-02-11 09:25:50 +00004672 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004673 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004674 }
Tim Northover1060eae2013-06-21 22:49:34 +00004675
Daniel Dunbar09d33622009-09-14 21:54:03 +00004676 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004677 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004678 return ABIArgInfo::getIgnore();
4679
Tim Northover5a1558e2014-11-07 22:30:50 +00004680 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004681 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4682 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004683 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004684 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004685 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004686 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004687 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004688 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004689 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004690 }
4691
Manman Ren6c30e132012-08-13 21:23:55 +00004692 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004693 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4694 // most 8-byte. We realign the indirect argument if type alignment is bigger
4695 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004696 uint64_t ABIAlign = 4;
4697 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4698 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004699 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004700 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004701
Manman Ren8cd99812012-11-06 04:58:01 +00004702 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004703 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004704 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004705 }
4706
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004707 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004708 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004709 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004710 // FIXME: Try to match the types of the arguments more accurately where
4711 // we can.
4712 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004713 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4714 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004715 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004716 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4717 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004718 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004719
Tim Northover5a1558e2014-11-07 22:30:50 +00004720 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004721}
4722
Chris Lattner458b2aa2010-07-29 02:16:43 +00004723static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004724 llvm::LLVMContext &VMContext) {
4725 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4726 // is called integer-like if its size is less than or equal to one word, and
4727 // the offset of each of its addressable sub-fields is zero.
4728
4729 uint64_t Size = Context.getTypeSize(Ty);
4730
4731 // Check that the type fits in a word.
4732 if (Size > 32)
4733 return false;
4734
4735 // FIXME: Handle vector types!
4736 if (Ty->isVectorType())
4737 return false;
4738
Daniel Dunbard53bac72009-09-14 02:20:34 +00004739 // Float types are never treated as "integer like".
4740 if (Ty->isRealFloatingType())
4741 return false;
4742
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004743 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004744 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004745 return true;
4746
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004747 // Small complex integer types are "integer like".
4748 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4749 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004750
4751 // Single element and zero sized arrays should be allowed, by the definition
4752 // above, but they are not.
4753
4754 // Otherwise, it must be a record type.
4755 const RecordType *RT = Ty->getAs<RecordType>();
4756 if (!RT) return false;
4757
4758 // Ignore records with flexible arrays.
4759 const RecordDecl *RD = RT->getDecl();
4760 if (RD->hasFlexibleArrayMember())
4761 return false;
4762
4763 // Check that all sub-fields are at offset 0, and are themselves "integer
4764 // like".
4765 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4766
4767 bool HadField = false;
4768 unsigned idx = 0;
4769 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4770 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004771 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004772
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004773 // Bit-fields are not addressable, we only need to verify they are "integer
4774 // like". We still have to disallow a subsequent non-bitfield, for example:
4775 // struct { int : 0; int x }
4776 // is non-integer like according to gcc.
4777 if (FD->isBitField()) {
4778 if (!RD->isUnion())
4779 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004780
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004781 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4782 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004783
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004784 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004785 }
4786
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004787 // Check if this field is at offset 0.
4788 if (Layout.getFieldOffset(idx) != 0)
4789 return false;
4790
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004791 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4792 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004793
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004794 // Only allow at most one field in a structure. This doesn't match the
4795 // wording above, but follows gcc in situations with a field following an
4796 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004797 if (!RD->isUnion()) {
4798 if (HadField)
4799 return false;
4800
4801 HadField = true;
4802 }
4803 }
4804
4805 return true;
4806}
4807
Oliver Stannard405bded2014-02-11 09:25:50 +00004808ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4809 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004810 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004811
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004812 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004813 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004814
Daniel Dunbar19964db2010-09-23 01:54:32 +00004815 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004816 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004817 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004818 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004819
John McCalla1dee5302010-08-22 10:59:02 +00004820 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004821 // Treat an enum type as its underlying type.
4822 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4823 RetTy = EnumTy->getDecl()->getIntegerType();
4824
Tim Northover5a1558e2014-11-07 22:30:50 +00004825 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4826 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004827 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004828
4829 // Are we following APCS?
4830 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004831 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004832 return ABIArgInfo::getIgnore();
4833
Daniel Dunbareedf1512010-02-01 23:31:19 +00004834 // Complex types are all returned as packed integers.
4835 //
4836 // FIXME: Consider using 2 x vector types if the back end handles them
4837 // correctly.
4838 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004839 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4840 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004841
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004842 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004843 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004844 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004845 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004846 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004847 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004848 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004849 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4850 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004851 }
4852
4853 // Otherwise return in memory.
4854 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004855 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004856
4857 // Otherwise this is an AAPCS variant.
4858
Chris Lattner458b2aa2010-07-29 02:16:43 +00004859 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004860 return ABIArgInfo::getIgnore();
4861
Bob Wilson1d9269a2011-11-02 04:51:36 +00004862 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004863 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004864 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004865 uint64_t Members;
4866 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004867 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004868 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004869 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004870 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004871 }
4872
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004873 // Aggregates <= 4 bytes are returned in r0; other aggregates
4874 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004875 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004876 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004877 if (getDataLayout().isBigEndian())
4878 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004879 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004880
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004881 // Return in the smallest viable integer type.
4882 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004883 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004884 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004885 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4886 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004887 }
4888
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004889 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004890}
4891
Manman Renfef9e312012-10-16 19:18:39 +00004892/// isIllegalVector - check whether Ty is an illegal vector type.
4893bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4894 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4895 // Check whether VT is legal.
4896 unsigned NumElements = VT->getNumElements();
4897 uint64_t Size = getContext().getTypeSize(VT);
4898 // NumElements should be power of 2.
4899 if ((NumElements & (NumElements - 1)) != 0)
4900 return true;
4901 // Size should be greater than 32 bits.
4902 return Size <= 32;
4903 }
4904 return false;
4905}
4906
Reid Klecknere9f6a712014-10-31 17:10:41 +00004907bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4908 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4909 // double, or 64-bit or 128-bit vectors.
4910 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4911 if (BT->getKind() == BuiltinType::Float ||
4912 BT->getKind() == BuiltinType::Double ||
4913 BT->getKind() == BuiltinType::LongDouble)
4914 return true;
4915 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4916 unsigned VecSize = getContext().getTypeSize(VT);
4917 if (VecSize == 64 || VecSize == 128)
4918 return true;
4919 }
4920 return false;
4921}
4922
4923bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4924 uint64_t Members) const {
4925 return Members <= 4;
4926}
4927
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004928llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004929 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004930 llvm::Type *BP = CGF.Int8PtrTy;
4931 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004932
4933 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004934 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004935 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004936
Tim Northover1711cc92013-06-21 23:05:33 +00004937 if (isEmptyRecord(getContext(), Ty, true)) {
4938 // These are ignored for parameter passing purposes.
4939 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4940 return Builder.CreateBitCast(Addr, PTy);
4941 }
4942
Manman Rencca54d02012-10-16 19:01:37 +00004943 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004944 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004945 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004946
4947 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4948 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004949 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4950 getABIKind() == ARMABIInfo::AAPCS)
4951 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4952 else
4953 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004954 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4955 if (isIllegalVectorType(Ty) && Size > 16) {
4956 IsIndirect = true;
4957 Size = 4;
4958 TyAlign = 4;
4959 }
Manman Rencca54d02012-10-16 19:01:37 +00004960
4961 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004962 if (TyAlign > 4) {
4963 assert((TyAlign & (TyAlign - 1)) == 0 &&
4964 "Alignment is not power of 2!");
4965 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4966 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4967 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004968 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004969 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004970
4971 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004972 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004973 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004974 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004975 "ap.next");
4976 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4977
Manman Renfef9e312012-10-16 19:18:39 +00004978 if (IsIndirect)
4979 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004980 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004981 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4982 // may not be correctly aligned for the vector type. We create an aligned
4983 // temporary space and copy the content over from ap.cur to the temporary
4984 // space. This is necessary if the natural alignment of the type is greater
4985 // than the ABI alignment.
4986 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4987 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4988 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4989 "var.align");
4990 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4991 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4992 Builder.CreateMemCpy(Dst, Src,
4993 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4994 TyAlign, false);
4995 Addr = AlignedTemp; //The content is in aligned location.
4996 }
4997 llvm::Type *PTy =
4998 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4999 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5000
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005001 return AddrTyped;
5002}
5003
Chris Lattner0cf24192010-06-28 20:05:43 +00005004//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005005// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005006//===----------------------------------------------------------------------===//
5007
5008namespace {
5009
Justin Holewinski83e96682012-05-24 17:43:12 +00005010class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005011public:
Justin Holewinski36837432013-03-30 14:38:24 +00005012 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005013
5014 ABIArgInfo classifyReturnType(QualType RetTy) const;
5015 ABIArgInfo classifyArgumentType(QualType Ty) const;
5016
Craig Topper4f12f102014-03-12 06:41:41 +00005017 void computeInfo(CGFunctionInfo &FI) const override;
5018 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5019 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005020};
5021
Justin Holewinski83e96682012-05-24 17:43:12 +00005022class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005023public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005024 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5025 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005026
5027 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5028 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005029private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005030 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5031 // resulting MDNode to the nvvm.annotations MDNode.
5032 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005033};
5034
Justin Holewinski83e96682012-05-24 17:43:12 +00005035ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005036 if (RetTy->isVoidType())
5037 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005038
5039 // note: this is different from default ABI
5040 if (!RetTy->isScalarType())
5041 return ABIArgInfo::getDirect();
5042
5043 // Treat an enum type as its underlying type.
5044 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5045 RetTy = EnumTy->getDecl()->getIntegerType();
5046
5047 return (RetTy->isPromotableIntegerType() ?
5048 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005049}
5050
Justin Holewinski83e96682012-05-24 17:43:12 +00005051ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005052 // Treat an enum type as its underlying type.
5053 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5054 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005055
Eli Bendersky95338a02014-10-29 13:43:21 +00005056 // Return aggregates type as indirect by value
5057 if (isAggregateTypeForABI(Ty))
5058 return ABIArgInfo::getIndirect(0, /* byval */ true);
5059
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005060 return (Ty->isPromotableIntegerType() ?
5061 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005062}
5063
Justin Holewinski83e96682012-05-24 17:43:12 +00005064void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005065 if (!getCXXABI().classifyReturnType(FI))
5066 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005067 for (auto &I : FI.arguments())
5068 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005069
5070 // Always honor user-specified calling convention.
5071 if (FI.getCallingConvention() != llvm::CallingConv::C)
5072 return;
5073
John McCall882987f2013-02-28 19:01:20 +00005074 FI.setEffectiveCallingConvention(getRuntimeCC());
5075}
5076
Justin Holewinski83e96682012-05-24 17:43:12 +00005077llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5078 CodeGenFunction &CFG) const {
5079 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005080}
5081
Justin Holewinski83e96682012-05-24 17:43:12 +00005082void NVPTXTargetCodeGenInfo::
5083SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5084 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005085 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5086 if (!FD) return;
5087
5088 llvm::Function *F = cast<llvm::Function>(GV);
5089
5090 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005091 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005092 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005093 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005094 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005095 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005096 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5097 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005098 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005099 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005100 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005101 }
Justin Holewinski38031972011-10-05 17:58:44 +00005102
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005103 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005104 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005105 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005106 // __global__ functions cannot be called from the device, we do not
5107 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005108 if (FD->hasAttr<CUDAGlobalAttr>()) {
5109 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5110 addNVVMMetadata(F, "kernel", 1);
5111 }
Artem Belevich7093e402015-04-21 22:55:54 +00005112 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005113 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005114 llvm::APSInt MaxThreads(32);
5115 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5116 if (MaxThreads > 0)
5117 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5118
5119 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5120 // not specified in __launch_bounds__ or if the user specified a 0 value,
5121 // we don't have to add a PTX directive.
5122 if (Attr->getMinBlocks()) {
5123 llvm::APSInt MinBlocks(32);
5124 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5125 if (MinBlocks > 0)
5126 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5127 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005128 }
5129 }
Justin Holewinski38031972011-10-05 17:58:44 +00005130 }
5131}
5132
Eli Benderskye06a2c42014-04-15 16:57:05 +00005133void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5134 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005135 llvm::Module *M = F->getParent();
5136 llvm::LLVMContext &Ctx = M->getContext();
5137
5138 // Get "nvvm.annotations" metadata node
5139 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5140
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005141 llvm::Metadata *MDVals[] = {
5142 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5143 llvm::ConstantAsMetadata::get(
5144 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005145 // Append metadata to nvvm.annotations
5146 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5147}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005148}
5149
5150//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005151// SystemZ ABI Implementation
5152//===----------------------------------------------------------------------===//
5153
5154namespace {
5155
5156class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005157 bool HasVector;
5158
Ulrich Weigand47445072013-05-06 16:26:41 +00005159public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005160 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5161 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005162
5163 bool isPromotableIntegerType(QualType Ty) const;
5164 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005165 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005166 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005167 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005168
5169 ABIArgInfo classifyReturnType(QualType RetTy) const;
5170 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5171
Craig Topper4f12f102014-03-12 06:41:41 +00005172 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005173 if (!getCXXABI().classifyReturnType(FI))
5174 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005175 for (auto &I : FI.arguments())
5176 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005177 }
5178
Craig Topper4f12f102014-03-12 06:41:41 +00005179 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5180 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005181};
5182
5183class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5184public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005185 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5186 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005187};
5188
5189}
5190
5191bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5192 // Treat an enum type as its underlying type.
5193 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5194 Ty = EnumTy->getDecl()->getIntegerType();
5195
5196 // Promotable integer types are required to be promoted by the ABI.
5197 if (Ty->isPromotableIntegerType())
5198 return true;
5199
5200 // 32-bit values must also be promoted.
5201 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5202 switch (BT->getKind()) {
5203 case BuiltinType::Int:
5204 case BuiltinType::UInt:
5205 return true;
5206 default:
5207 return false;
5208 }
5209 return false;
5210}
5211
5212bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005213 return (Ty->isAnyComplexType() ||
5214 Ty->isVectorType() ||
5215 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005216}
5217
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005218bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5219 return (HasVector &&
5220 Ty->isVectorType() &&
5221 getContext().getTypeSize(Ty) <= 128);
5222}
5223
Ulrich Weigand47445072013-05-06 16:26:41 +00005224bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5225 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5226 switch (BT->getKind()) {
5227 case BuiltinType::Float:
5228 case BuiltinType::Double:
5229 return true;
5230 default:
5231 return false;
5232 }
5233
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005234 return false;
5235}
5236
5237QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005238 if (const RecordType *RT = Ty->getAsStructureType()) {
5239 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005240 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005241
5242 // If this is a C++ record, check the bases first.
5243 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005244 for (const auto &I : CXXRD->bases()) {
5245 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005246
5247 // Empty bases don't affect things either way.
5248 if (isEmptyRecord(getContext(), Base, true))
5249 continue;
5250
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005251 if (!Found.isNull())
5252 return Ty;
5253 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005254 }
5255
5256 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005257 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005258 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005259 // Unlike isSingleElementStruct(), empty structure and array fields
5260 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005261 if (getContext().getLangOpts().CPlusPlus &&
5262 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5263 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005264
5265 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005266 // Nested structures still do though.
5267 if (!Found.isNull())
5268 return Ty;
5269 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005270 }
5271
5272 // Unlike isSingleElementStruct(), trailing padding is allowed.
5273 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005274 if (!Found.isNull())
5275 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005276 }
5277
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005278 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005279}
5280
5281llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5282 CodeGenFunction &CGF) const {
5283 // Assume that va_list type is correct; should be pointer to LLVM type:
5284 // struct {
5285 // i64 __gpr;
5286 // i64 __fpr;
5287 // i8 *__overflow_arg_area;
5288 // i8 *__reg_save_area;
5289 // };
5290
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005291 // Every non-vector argument occupies 8 bytes and is passed by preference
5292 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5293 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005294 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005295 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5296 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005297 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005298 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005299 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005300 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005301 unsigned UnpaddedBitSize;
5302 if (IsIndirect) {
5303 APTy = llvm::PointerType::getUnqual(APTy);
5304 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005305 } else {
5306 if (AI.getCoerceToType())
5307 ArgTy = AI.getCoerceToType();
5308 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005309 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005310 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005311 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005312 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005313 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5314
5315 unsigned PaddedSize = PaddedBitSize / 8;
5316 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5317
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005318 llvm::Type *IndexTy = CGF.Int64Ty;
5319 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5320
5321 if (IsVector) {
5322 // Work out the address of a vector argument on the stack.
5323 // Vector arguments are always passed in the high bits of a
5324 // single (8 byte) or double (16 byte) stack slot.
5325 llvm::Value *OverflowArgAreaPtr =
5326 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5327 "overflow_arg_area_ptr");
5328 llvm::Value *OverflowArgArea =
5329 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5330 llvm::Value *MemAddr =
5331 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5332
5333 // Update overflow_arg_area_ptr pointer
5334 llvm::Value *NewOverflowArgArea =
5335 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5336 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5337
5338 return MemAddr;
5339 }
5340
Ulrich Weigand47445072013-05-06 16:26:41 +00005341 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5342 if (InFPRs) {
5343 MaxRegs = 4; // Maximum of 4 FPR arguments
5344 RegCountField = 1; // __fpr
5345 RegSaveIndex = 16; // save offset for f0
5346 RegPadding = 0; // floats are passed in the high bits of an FPR
5347 } else {
5348 MaxRegs = 5; // Maximum of 5 GPR arguments
5349 RegCountField = 0; // __gpr
5350 RegSaveIndex = 2; // save offset for r2
5351 RegPadding = Padding; // values are passed in the low bits of a GPR
5352 }
5353
David Blaikie2e804282015-04-05 22:47:07 +00005354 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5355 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005356 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005357 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5358 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005359 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005360
5361 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5362 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5363 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5364 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5365
5366 // Emit code to load the value if it was passed in registers.
5367 CGF.EmitBlock(InRegBlock);
5368
5369 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005370 llvm::Value *ScaledRegCount =
5371 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5372 llvm::Value *RegBase =
5373 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5374 llvm::Value *RegOffset =
5375 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5376 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005377 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005378 llvm::Value *RegSaveArea =
5379 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5380 llvm::Value *RawRegAddr =
5381 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5382 llvm::Value *RegAddr =
5383 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5384
5385 // Update the register count
5386 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5387 llvm::Value *NewRegCount =
5388 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5389 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5390 CGF.EmitBranch(ContBlock);
5391
5392 // Emit code to load the value if it was passed in memory.
5393 CGF.EmitBlock(InMemBlock);
5394
5395 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005396 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5397 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005398 llvm::Value *OverflowArgArea =
5399 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5400 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5401 llvm::Value *RawMemAddr =
5402 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5403 llvm::Value *MemAddr =
5404 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5405
5406 // Update overflow_arg_area_ptr pointer
5407 llvm::Value *NewOverflowArgArea =
5408 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5409 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5410 CGF.EmitBranch(ContBlock);
5411
5412 // Return the appropriate result.
5413 CGF.EmitBlock(ContBlock);
5414 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5415 ResAddr->addIncoming(RegAddr, InRegBlock);
5416 ResAddr->addIncoming(MemAddr, InMemBlock);
5417
5418 if (IsIndirect)
5419 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5420
5421 return ResAddr;
5422}
5423
Ulrich Weigand47445072013-05-06 16:26:41 +00005424ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5425 if (RetTy->isVoidType())
5426 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005427 if (isVectorArgumentType(RetTy))
5428 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005429 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5430 return ABIArgInfo::getIndirect(0);
5431 return (isPromotableIntegerType(RetTy) ?
5432 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5433}
5434
5435ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5436 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005437 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005438 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5439
5440 // Integers and enums are extended to full register width.
5441 if (isPromotableIntegerType(Ty))
5442 return ABIArgInfo::getExtend();
5443
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005444 // Handle vector types and vector-like structure types. Note that
5445 // as opposed to float-like structure types, we do not allow any
5446 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005447 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005448 QualType SingleElementTy = GetSingleElementType(Ty);
5449 if (isVectorArgumentType(SingleElementTy) &&
5450 getContext().getTypeSize(SingleElementTy) == Size)
5451 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5452
5453 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005454 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005455 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005456
5457 // Handle small structures.
5458 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5459 // Structures with flexible arrays have variable length, so really
5460 // fail the size test above.
5461 const RecordDecl *RD = RT->getDecl();
5462 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005463 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005464
5465 // The structure is passed as an unextended integer, a float, or a double.
5466 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005467 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005468 assert(Size == 32 || Size == 64);
5469 if (Size == 32)
5470 PassTy = llvm::Type::getFloatTy(getVMContext());
5471 else
5472 PassTy = llvm::Type::getDoubleTy(getVMContext());
5473 } else
5474 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5475 return ABIArgInfo::getDirect(PassTy);
5476 }
5477
5478 // Non-structure compounds are passed indirectly.
5479 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005480 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005481
Craig Topper8a13c412014-05-21 05:09:00 +00005482 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005483}
5484
5485//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005486// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005487//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005488
5489namespace {
5490
5491class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5492public:
Chris Lattner2b037972010-07-29 02:01:43 +00005493 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5494 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005495 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005496 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005497};
5498
5499}
5500
5501void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5502 llvm::GlobalValue *GV,
5503 CodeGen::CodeGenModule &M) const {
5504 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5505 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5506 // Handle 'interrupt' attribute:
5507 llvm::Function *F = cast<llvm::Function>(GV);
5508
5509 // Step 1: Set ISR calling convention.
5510 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5511
5512 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005513 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005514
5515 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005516 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005517 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5518 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005519 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005520 }
5521}
5522
Chris Lattner0cf24192010-06-28 20:05:43 +00005523//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005524// MIPS ABI Implementation. This works for both little-endian and
5525// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005526//===----------------------------------------------------------------------===//
5527
John McCall943fae92010-05-27 06:19:26 +00005528namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005529class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005530 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005531 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5532 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005533 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005534 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005535 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005536 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005537public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005538 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005539 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005540 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005541
5542 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005543 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005544 void computeInfo(CGFunctionInfo &FI) const override;
5545 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5546 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005547};
5548
John McCall943fae92010-05-27 06:19:26 +00005549class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005550 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005551public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005552 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5553 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005554 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005555
Craig Topper4f12f102014-03-12 06:41:41 +00005556 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005557 return 29;
5558 }
5559
Reed Kotler373feca2013-01-16 17:10:28 +00005560 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005561 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005562 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5563 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005564 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005565 if (FD->hasAttr<Mips16Attr>()) {
5566 Fn->addFnAttr("mips16");
5567 }
5568 else if (FD->hasAttr<NoMips16Attr>()) {
5569 Fn->addFnAttr("nomips16");
5570 }
Reed Kotler373feca2013-01-16 17:10:28 +00005571 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005572
John McCall943fae92010-05-27 06:19:26 +00005573 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005574 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005575
Craig Topper4f12f102014-03-12 06:41:41 +00005576 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005577 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005578 }
John McCall943fae92010-05-27 06:19:26 +00005579};
5580}
5581
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005582void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005583 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005584 llvm::IntegerType *IntTy =
5585 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005586
5587 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5588 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5589 ArgList.push_back(IntTy);
5590
5591 // If necessary, add one more integer type to ArgList.
5592 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5593
5594 if (R)
5595 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005596}
5597
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005598// In N32/64, an aligned double precision floating point field is passed in
5599// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005600llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005601 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5602
5603 if (IsO32) {
5604 CoerceToIntArgs(TySize, ArgList);
5605 return llvm::StructType::get(getVMContext(), ArgList);
5606 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005607
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005608 if (Ty->isComplexType())
5609 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005610
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005611 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005612
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005613 // Unions/vectors are passed in integer registers.
5614 if (!RT || !RT->isStructureOrClassType()) {
5615 CoerceToIntArgs(TySize, ArgList);
5616 return llvm::StructType::get(getVMContext(), ArgList);
5617 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005618
5619 const RecordDecl *RD = RT->getDecl();
5620 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005621 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005622
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005623 uint64_t LastOffset = 0;
5624 unsigned idx = 0;
5625 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5626
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005627 // Iterate over fields in the struct/class and check if there are any aligned
5628 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005629 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5630 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005631 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005632 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5633
5634 if (!BT || BT->getKind() != BuiltinType::Double)
5635 continue;
5636
5637 uint64_t Offset = Layout.getFieldOffset(idx);
5638 if (Offset % 64) // Ignore doubles that are not aligned.
5639 continue;
5640
5641 // Add ((Offset - LastOffset) / 64) args of type i64.
5642 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5643 ArgList.push_back(I64);
5644
5645 // Add double type.
5646 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5647 LastOffset = Offset + 64;
5648 }
5649
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005650 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5651 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005652
5653 return llvm::StructType::get(getVMContext(), ArgList);
5654}
5655
Akira Hatanakaddd66342013-10-29 18:41:15 +00005656llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5657 uint64_t Offset) const {
5658 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005659 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005660
Akira Hatanakaddd66342013-10-29 18:41:15 +00005661 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005662}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005663
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005664ABIArgInfo
5665MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005666 Ty = useFirstFieldIfTransparentUnion(Ty);
5667
Akira Hatanaka1632af62012-01-09 19:31:25 +00005668 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005669 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005670 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005671
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005672 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5673 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005674 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5675 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005676
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005677 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005678 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005679 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005680 return ABIArgInfo::getIgnore();
5681
Mark Lacey3825e832013-10-06 01:33:34 +00005682 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005683 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005684 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005685 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005686
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005687 // If we have reached here, aggregates are passed directly by coercing to
5688 // another structure type. Padding is inserted if the offset of the
5689 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005690 ABIArgInfo ArgInfo =
5691 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5692 getPaddingType(OrigOffset, CurrOffset));
5693 ArgInfo.setInReg(true);
5694 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005695 }
5696
5697 // Treat an enum type as its underlying type.
5698 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5699 Ty = EnumTy->getDecl()->getIntegerType();
5700
Daniel Sanders5b445b32014-10-24 14:42:42 +00005701 // All integral types are promoted to the GPR width.
5702 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005703 return ABIArgInfo::getExtend();
5704
Akira Hatanakaddd66342013-10-29 18:41:15 +00005705 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005706 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005707}
5708
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005709llvm::Type*
5710MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005711 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005712 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005713
Akira Hatanakab6f74432012-02-09 18:49:26 +00005714 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005715 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005716 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5717 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005718
Akira Hatanakab6f74432012-02-09 18:49:26 +00005719 // N32/64 returns struct/classes in floating point registers if the
5720 // following conditions are met:
5721 // 1. The size of the struct/class is no larger than 128-bit.
5722 // 2. The struct/class has one or two fields all of which are floating
5723 // point types.
5724 // 3. The offset of the first field is zero (this follows what gcc does).
5725 //
5726 // Any other composite results are returned in integer registers.
5727 //
5728 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5729 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5730 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005731 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005732
Akira Hatanakab6f74432012-02-09 18:49:26 +00005733 if (!BT || !BT->isFloatingPoint())
5734 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005735
David Blaikie2d7c57e2012-04-30 02:36:29 +00005736 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005737 }
5738
5739 if (b == e)
5740 return llvm::StructType::get(getVMContext(), RTList,
5741 RD->hasAttr<PackedAttr>());
5742
5743 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005744 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005745 }
5746
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005747 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005748 return llvm::StructType::get(getVMContext(), RTList);
5749}
5750
Akira Hatanakab579fe52011-06-02 00:09:17 +00005751ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005752 uint64_t Size = getContext().getTypeSize(RetTy);
5753
Daniel Sandersed39f582014-09-04 13:28:14 +00005754 if (RetTy->isVoidType())
5755 return ABIArgInfo::getIgnore();
5756
5757 // O32 doesn't treat zero-sized structs differently from other structs.
5758 // However, N32/N64 ignores zero sized return values.
5759 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005760 return ABIArgInfo::getIgnore();
5761
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005762 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005763 if (Size <= 128) {
5764 if (RetTy->isAnyComplexType())
5765 return ABIArgInfo::getDirect();
5766
Daniel Sanderse5018b62014-09-04 15:05:39 +00005767 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005768 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005769 if (!IsO32 ||
5770 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5771 ABIArgInfo ArgInfo =
5772 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5773 ArgInfo.setInReg(true);
5774 return ArgInfo;
5775 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005776 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005777
5778 return ABIArgInfo::getIndirect(0);
5779 }
5780
5781 // Treat an enum type as its underlying type.
5782 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5783 RetTy = EnumTy->getDecl()->getIntegerType();
5784
5785 return (RetTy->isPromotableIntegerType() ?
5786 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5787}
5788
5789void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005790 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005791 if (!getCXXABI().classifyReturnType(FI))
5792 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005793
5794 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005795 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005796
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005797 for (auto &I : FI.arguments())
5798 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005799}
5800
5801llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5802 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005803 llvm::Type *BP = CGF.Int8PtrTy;
5804 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005805
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005806 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5807 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005808 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005809 unsigned PtrWidth = getTarget().getPointerWidth(0);
5810 if ((Ty->isIntegerType() &&
5811 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5812 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005813 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5814 Ty->isSignedIntegerType());
5815 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005816
5817 CGBuilderTy &Builder = CGF.Builder;
5818 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5819 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005820 int64_t TypeAlign =
5821 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005822 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5823 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005824 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5825
5826 if (TypeAlign > MinABIStackAlignInBytes) {
5827 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5828 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5829 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5830 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5831 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5832 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5833 }
5834 else
5835 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5836
5837 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5838 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005839 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5840 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005841 llvm::Value *NextAddr =
5842 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5843 "ap.next");
5844 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5845
5846 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005847}
5848
John McCall943fae92010-05-27 06:19:26 +00005849bool
5850MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5851 llvm::Value *Address) const {
5852 // This information comes from gcc's implementation, which seems to
5853 // as canonical as it gets.
5854
John McCall943fae92010-05-27 06:19:26 +00005855 // Everything on MIPS is 4 bytes. Double-precision FP registers
5856 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005857 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005858
5859 // 0-31 are the general purpose registers, $0 - $31.
5860 // 32-63 are the floating-point registers, $f0 - $f31.
5861 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5862 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005863 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005864
5865 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5866 // They are one bit wide and ignored here.
5867
5868 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5869 // (coprocessor 1 is the FP unit)
5870 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5871 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5872 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005873 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005874 return false;
5875}
5876
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005877//===----------------------------------------------------------------------===//
5878// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5879// Currently subclassed only to implement custom OpenCL C function attribute
5880// handling.
5881//===----------------------------------------------------------------------===//
5882
5883namespace {
5884
5885class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5886public:
5887 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5888 : DefaultTargetCodeGenInfo(CGT) {}
5889
Craig Topper4f12f102014-03-12 06:41:41 +00005890 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5891 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005892};
5893
5894void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5895 llvm::GlobalValue *GV,
5896 CodeGen::CodeGenModule &M) const {
5897 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5898 if (!FD) return;
5899
5900 llvm::Function *F = cast<llvm::Function>(GV);
5901
David Blaikiebbafb8a2012-03-11 07:00:24 +00005902 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005903 if (FD->hasAttr<OpenCLKernelAttr>()) {
5904 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005905 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005906 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5907 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005908 // Convert the reqd_work_group_size() attributes to metadata.
5909 llvm::LLVMContext &Context = F->getContext();
5910 llvm::NamedMDNode *OpenCLMetadata =
5911 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5912
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005913 SmallVector<llvm::Metadata *, 5> Operands;
5914 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005915
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005916 Operands.push_back(
5917 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5918 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5919 Operands.push_back(
5920 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5921 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5922 Operands.push_back(
5923 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5924 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005925
5926 // Add a boolean constant operand for "required" (true) or "hint" (false)
5927 // for implementing the work_group_size_hint attr later. Currently
5928 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005929 Operands.push_back(
5930 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005931 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5932 }
5933 }
5934 }
5935}
5936
5937}
John McCall943fae92010-05-27 06:19:26 +00005938
Tony Linthicum76329bf2011-12-12 21:14:55 +00005939//===----------------------------------------------------------------------===//
5940// Hexagon ABI Implementation
5941//===----------------------------------------------------------------------===//
5942
5943namespace {
5944
5945class HexagonABIInfo : public ABIInfo {
5946
5947
5948public:
5949 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5950
5951private:
5952
5953 ABIArgInfo classifyReturnType(QualType RetTy) const;
5954 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5955
Craig Topper4f12f102014-03-12 06:41:41 +00005956 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005957
Craig Topper4f12f102014-03-12 06:41:41 +00005958 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5959 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005960};
5961
5962class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5963public:
5964 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5965 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5966
Craig Topper4f12f102014-03-12 06:41:41 +00005967 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005968 return 29;
5969 }
5970};
5971
5972}
5973
5974void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005975 if (!getCXXABI().classifyReturnType(FI))
5976 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005977 for (auto &I : FI.arguments())
5978 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005979}
5980
5981ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5982 if (!isAggregateTypeForABI(Ty)) {
5983 // Treat an enum type as its underlying type.
5984 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5985 Ty = EnumTy->getDecl()->getIntegerType();
5986
5987 return (Ty->isPromotableIntegerType() ?
5988 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5989 }
5990
5991 // Ignore empty records.
5992 if (isEmptyRecord(getContext(), Ty, true))
5993 return ABIArgInfo::getIgnore();
5994
Mark Lacey3825e832013-10-06 01:33:34 +00005995 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005996 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005997
5998 uint64_t Size = getContext().getTypeSize(Ty);
5999 if (Size > 64)
6000 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6001 // Pass in the smallest viable integer type.
6002 else if (Size > 32)
6003 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6004 else if (Size > 16)
6005 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6006 else if (Size > 8)
6007 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6008 else
6009 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6010}
6011
6012ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6013 if (RetTy->isVoidType())
6014 return ABIArgInfo::getIgnore();
6015
6016 // Large vector types should be returned via memory.
6017 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6018 return ABIArgInfo::getIndirect(0);
6019
6020 if (!isAggregateTypeForABI(RetTy)) {
6021 // Treat an enum type as its underlying type.
6022 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6023 RetTy = EnumTy->getDecl()->getIntegerType();
6024
6025 return (RetTy->isPromotableIntegerType() ?
6026 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6027 }
6028
Tony Linthicum76329bf2011-12-12 21:14:55 +00006029 if (isEmptyRecord(getContext(), RetTy, true))
6030 return ABIArgInfo::getIgnore();
6031
6032 // Aggregates <= 8 bytes are returned in r0; other aggregates
6033 // are returned indirectly.
6034 uint64_t Size = getContext().getTypeSize(RetTy);
6035 if (Size <= 64) {
6036 // Return in the smallest viable integer type.
6037 if (Size <= 8)
6038 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6039 if (Size <= 16)
6040 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6041 if (Size <= 32)
6042 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6043 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6044 }
6045
6046 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6047}
6048
6049llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006050 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006051 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006052 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006053
6054 CGBuilderTy &Builder = CGF.Builder;
6055 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6056 "ap");
6057 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6058 llvm::Type *PTy =
6059 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6060 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6061
6062 uint64_t Offset =
6063 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6064 llvm::Value *NextAddr =
6065 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6066 "ap.next");
6067 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6068
6069 return AddrTyped;
6070}
6071
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006072//===----------------------------------------------------------------------===//
6073// AMDGPU ABI Implementation
6074//===----------------------------------------------------------------------===//
6075
6076namespace {
6077
6078class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6079public:
6080 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6081 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6082 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6083 CodeGen::CodeGenModule &M) const override;
6084};
6085
6086}
6087
6088void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
6089 const Decl *D,
6090 llvm::GlobalValue *GV,
6091 CodeGen::CodeGenModule &M) const {
6092 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6093 if (!FD)
6094 return;
6095
6096 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6097 llvm::Function *F = cast<llvm::Function>(GV);
6098 uint32_t NumVGPR = Attr->getNumVGPR();
6099 if (NumVGPR != 0)
6100 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6101 }
6102
6103 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6104 llvm::Function *F = cast<llvm::Function>(GV);
6105 unsigned NumSGPR = Attr->getNumSGPR();
6106 if (NumSGPR != 0)
6107 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6108 }
6109}
6110
Tony Linthicum76329bf2011-12-12 21:14:55 +00006111
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006112//===----------------------------------------------------------------------===//
6113// SPARC v9 ABI Implementation.
6114// Based on the SPARC Compliance Definition version 2.4.1.
6115//
6116// Function arguments a mapped to a nominal "parameter array" and promoted to
6117// registers depending on their type. Each argument occupies 8 or 16 bytes in
6118// the array, structs larger than 16 bytes are passed indirectly.
6119//
6120// One case requires special care:
6121//
6122// struct mixed {
6123// int i;
6124// float f;
6125// };
6126//
6127// When a struct mixed is passed by value, it only occupies 8 bytes in the
6128// parameter array, but the int is passed in an integer register, and the float
6129// is passed in a floating point register. This is represented as two arguments
6130// with the LLVM IR inreg attribute:
6131//
6132// declare void f(i32 inreg %i, float inreg %f)
6133//
6134// The code generator will only allocate 4 bytes from the parameter array for
6135// the inreg arguments. All other arguments are allocated a multiple of 8
6136// bytes.
6137//
6138namespace {
6139class SparcV9ABIInfo : public ABIInfo {
6140public:
6141 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6142
6143private:
6144 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006145 void computeInfo(CGFunctionInfo &FI) const override;
6146 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6147 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006148
6149 // Coercion type builder for structs passed in registers. The coercion type
6150 // serves two purposes:
6151 //
6152 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6153 // in registers.
6154 // 2. Expose aligned floating point elements as first-level elements, so the
6155 // code generator knows to pass them in floating point registers.
6156 //
6157 // We also compute the InReg flag which indicates that the struct contains
6158 // aligned 32-bit floats.
6159 //
6160 struct CoerceBuilder {
6161 llvm::LLVMContext &Context;
6162 const llvm::DataLayout &DL;
6163 SmallVector<llvm::Type*, 8> Elems;
6164 uint64_t Size;
6165 bool InReg;
6166
6167 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6168 : Context(c), DL(dl), Size(0), InReg(false) {}
6169
6170 // Pad Elems with integers until Size is ToSize.
6171 void pad(uint64_t ToSize) {
6172 assert(ToSize >= Size && "Cannot remove elements");
6173 if (ToSize == Size)
6174 return;
6175
6176 // Finish the current 64-bit word.
6177 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6178 if (Aligned > Size && Aligned <= ToSize) {
6179 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6180 Size = Aligned;
6181 }
6182
6183 // Add whole 64-bit words.
6184 while (Size + 64 <= ToSize) {
6185 Elems.push_back(llvm::Type::getInt64Ty(Context));
6186 Size += 64;
6187 }
6188
6189 // Final in-word padding.
6190 if (Size < ToSize) {
6191 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6192 Size = ToSize;
6193 }
6194 }
6195
6196 // Add a floating point element at Offset.
6197 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6198 // Unaligned floats are treated as integers.
6199 if (Offset % Bits)
6200 return;
6201 // The InReg flag is only required if there are any floats < 64 bits.
6202 if (Bits < 64)
6203 InReg = true;
6204 pad(Offset);
6205 Elems.push_back(Ty);
6206 Size = Offset + Bits;
6207 }
6208
6209 // Add a struct type to the coercion type, starting at Offset (in bits).
6210 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6211 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6212 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6213 llvm::Type *ElemTy = StrTy->getElementType(i);
6214 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6215 switch (ElemTy->getTypeID()) {
6216 case llvm::Type::StructTyID:
6217 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6218 break;
6219 case llvm::Type::FloatTyID:
6220 addFloat(ElemOffset, ElemTy, 32);
6221 break;
6222 case llvm::Type::DoubleTyID:
6223 addFloat(ElemOffset, ElemTy, 64);
6224 break;
6225 case llvm::Type::FP128TyID:
6226 addFloat(ElemOffset, ElemTy, 128);
6227 break;
6228 case llvm::Type::PointerTyID:
6229 if (ElemOffset % 64 == 0) {
6230 pad(ElemOffset);
6231 Elems.push_back(ElemTy);
6232 Size += 64;
6233 }
6234 break;
6235 default:
6236 break;
6237 }
6238 }
6239 }
6240
6241 // Check if Ty is a usable substitute for the coercion type.
6242 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006243 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006244 }
6245
6246 // Get the coercion type as a literal struct type.
6247 llvm::Type *getType() const {
6248 if (Elems.size() == 1)
6249 return Elems.front();
6250 else
6251 return llvm::StructType::get(Context, Elems);
6252 }
6253 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006254};
6255} // end anonymous namespace
6256
6257ABIArgInfo
6258SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6259 if (Ty->isVoidType())
6260 return ABIArgInfo::getIgnore();
6261
6262 uint64_t Size = getContext().getTypeSize(Ty);
6263
6264 // Anything too big to fit in registers is passed with an explicit indirect
6265 // pointer / sret pointer.
6266 if (Size > SizeLimit)
6267 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6268
6269 // Treat an enum type as its underlying type.
6270 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6271 Ty = EnumTy->getDecl()->getIntegerType();
6272
6273 // Integer types smaller than a register are extended.
6274 if (Size < 64 && Ty->isIntegerType())
6275 return ABIArgInfo::getExtend();
6276
6277 // Other non-aggregates go in registers.
6278 if (!isAggregateTypeForABI(Ty))
6279 return ABIArgInfo::getDirect();
6280
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006281 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6282 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6283 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6284 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6285
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006286 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006287 // Build a coercion type from the LLVM struct type.
6288 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6289 if (!StrTy)
6290 return ABIArgInfo::getDirect();
6291
6292 CoerceBuilder CB(getVMContext(), getDataLayout());
6293 CB.addStruct(0, StrTy);
6294 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6295
6296 // Try to use the original type for coercion.
6297 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6298
6299 if (CB.InReg)
6300 return ABIArgInfo::getDirectInReg(CoerceTy);
6301 else
6302 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006303}
6304
6305llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6306 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006307 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6308 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6309 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6310 AI.setCoerceToType(ArgTy);
6311
6312 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6313 CGBuilderTy &Builder = CGF.Builder;
6314 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6315 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6316 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6317 llvm::Value *ArgAddr;
6318 unsigned Stride;
6319
6320 switch (AI.getKind()) {
6321 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006322 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006323 llvm_unreachable("Unsupported ABI kind for va_arg");
6324
6325 case ABIArgInfo::Extend:
6326 Stride = 8;
6327 ArgAddr = Builder
6328 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6329 "extend");
6330 break;
6331
6332 case ABIArgInfo::Direct:
6333 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6334 ArgAddr = Addr;
6335 break;
6336
6337 case ABIArgInfo::Indirect:
6338 Stride = 8;
6339 ArgAddr = Builder.CreateBitCast(Addr,
6340 llvm::PointerType::getUnqual(ArgPtrTy),
6341 "indirect");
6342 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6343 break;
6344
6345 case ABIArgInfo::Ignore:
6346 return llvm::UndefValue::get(ArgPtrTy);
6347 }
6348
6349 // Update VAList.
6350 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6351 Builder.CreateStore(Addr, VAListAddrAsBPP);
6352
6353 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006354}
6355
6356void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6357 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006358 for (auto &I : FI.arguments())
6359 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006360}
6361
6362namespace {
6363class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6364public:
6365 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6366 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006367
Craig Topper4f12f102014-03-12 06:41:41 +00006368 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006369 return 14;
6370 }
6371
6372 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006373 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006374};
6375} // end anonymous namespace
6376
Roman Divackyf02c9942014-02-24 18:46:27 +00006377bool
6378SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6379 llvm::Value *Address) const {
6380 // This is calculated from the LLVM and GCC tables and verified
6381 // against gcc output. AFAIK all ABIs use the same encoding.
6382
6383 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6384
6385 llvm::IntegerType *i8 = CGF.Int8Ty;
6386 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6387 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6388
6389 // 0-31: the 8-byte general-purpose registers
6390 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6391
6392 // 32-63: f0-31, the 4-byte floating-point registers
6393 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6394
6395 // Y = 64
6396 // PSR = 65
6397 // WIM = 66
6398 // TBR = 67
6399 // PC = 68
6400 // NPC = 69
6401 // FSR = 70
6402 // CSR = 71
6403 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6404
6405 // 72-87: d0-15, the 8-byte floating-point registers
6406 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6407
6408 return false;
6409}
6410
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006411
Robert Lytton0e076492013-08-13 09:43:10 +00006412//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006413// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006414//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006415
Robert Lytton0e076492013-08-13 09:43:10 +00006416namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006417
6418/// A SmallStringEnc instance is used to build up the TypeString by passing
6419/// it by reference between functions that append to it.
6420typedef llvm::SmallString<128> SmallStringEnc;
6421
6422/// TypeStringCache caches the meta encodings of Types.
6423///
6424/// The reason for caching TypeStrings is two fold:
6425/// 1. To cache a type's encoding for later uses;
6426/// 2. As a means to break recursive member type inclusion.
6427///
6428/// A cache Entry can have a Status of:
6429/// NonRecursive: The type encoding is not recursive;
6430/// Recursive: The type encoding is recursive;
6431/// Incomplete: An incomplete TypeString;
6432/// IncompleteUsed: An incomplete TypeString that has been used in a
6433/// Recursive type encoding.
6434///
6435/// A NonRecursive entry will have all of its sub-members expanded as fully
6436/// as possible. Whilst it may contain types which are recursive, the type
6437/// itself is not recursive and thus its encoding may be safely used whenever
6438/// the type is encountered.
6439///
6440/// A Recursive entry will have all of its sub-members expanded as fully as
6441/// possible. The type itself is recursive and it may contain other types which
6442/// are recursive. The Recursive encoding must not be used during the expansion
6443/// of a recursive type's recursive branch. For simplicity the code uses
6444/// IncompleteCount to reject all usage of Recursive encodings for member types.
6445///
6446/// An Incomplete entry is always a RecordType and only encodes its
6447/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6448/// are placed into the cache during type expansion as a means to identify and
6449/// handle recursive inclusion of types as sub-members. If there is recursion
6450/// the entry becomes IncompleteUsed.
6451///
6452/// During the expansion of a RecordType's members:
6453///
6454/// If the cache contains a NonRecursive encoding for the member type, the
6455/// cached encoding is used;
6456///
6457/// If the cache contains a Recursive encoding for the member type, the
6458/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6459///
6460/// If the member is a RecordType, an Incomplete encoding is placed into the
6461/// cache to break potential recursive inclusion of itself as a sub-member;
6462///
6463/// Once a member RecordType has been expanded, its temporary incomplete
6464/// entry is removed from the cache. If a Recursive encoding was swapped out
6465/// it is swapped back in;
6466///
6467/// If an incomplete entry is used to expand a sub-member, the incomplete
6468/// entry is marked as IncompleteUsed. The cache keeps count of how many
6469/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6470///
6471/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6472/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6473/// Else the member is part of a recursive type and thus the recursion has
6474/// been exited too soon for the encoding to be correct for the member.
6475///
6476class TypeStringCache {
6477 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6478 struct Entry {
6479 std::string Str; // The encoded TypeString for the type.
6480 enum Status State; // Information about the encoding in 'Str'.
6481 std::string Swapped; // A temporary place holder for a Recursive encoding
6482 // during the expansion of RecordType's members.
6483 };
6484 std::map<const IdentifierInfo *, struct Entry> Map;
6485 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6486 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6487public:
Robert Lyttond263f142014-05-06 09:38:54 +00006488 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006489 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6490 bool removeIncomplete(const IdentifierInfo *ID);
6491 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6492 bool IsRecursive);
6493 StringRef lookupStr(const IdentifierInfo *ID);
6494};
6495
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006496/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006497/// FieldEncoding is a helper for this ordering process.
6498class FieldEncoding {
6499 bool HasName;
6500 std::string Enc;
6501public:
6502 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6503 StringRef str() {return Enc.c_str();};
6504 bool operator<(const FieldEncoding &rhs) const {
6505 if (HasName != rhs.HasName) return HasName;
6506 return Enc < rhs.Enc;
6507 }
6508};
6509
Robert Lytton7d1db152013-08-19 09:46:39 +00006510class XCoreABIInfo : public DefaultABIInfo {
6511public:
6512 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006513 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6514 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006515};
6516
Robert Lyttond21e2d72014-03-03 13:45:29 +00006517class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006518 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006519public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006520 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006521 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006522 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6523 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006524};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006525
Robert Lytton2d196952013-10-11 10:29:34 +00006526} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006527
Robert Lytton7d1db152013-08-19 09:46:39 +00006528llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6529 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006530 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006531
Robert Lytton2d196952013-10-11 10:29:34 +00006532 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006533 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6534 CGF.Int8PtrPtrTy);
6535 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006536
Robert Lytton2d196952013-10-11 10:29:34 +00006537 // Handle the argument.
6538 ABIArgInfo AI = classifyArgumentType(Ty);
6539 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6540 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6541 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006542 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006543 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006544 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006545 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006546 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006547 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006548 llvm_unreachable("Unsupported ABI kind for va_arg");
6549 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006550 Val = llvm::UndefValue::get(ArgPtrTy);
6551 ArgSize = 0;
6552 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006553 case ABIArgInfo::Extend:
6554 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006555 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6556 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6557 if (ArgSize < 4)
6558 ArgSize = 4;
6559 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006560 case ABIArgInfo::Indirect:
6561 llvm::Value *ArgAddr;
6562 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6563 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006564 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6565 ArgSize = 4;
6566 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006567 }
Robert Lytton2d196952013-10-11 10:29:34 +00006568
6569 // Increment the VAList.
6570 if (ArgSize) {
6571 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6572 Builder.CreateStore(APN, VAListAddrAsBPP);
6573 }
6574 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006575}
Robert Lytton0e076492013-08-13 09:43:10 +00006576
Robert Lytton844aeeb2014-05-02 09:33:20 +00006577/// During the expansion of a RecordType, an incomplete TypeString is placed
6578/// into the cache as a means to identify and break recursion.
6579/// If there is a Recursive encoding in the cache, it is swapped out and will
6580/// be reinserted by removeIncomplete().
6581/// All other types of encoding should have been used rather than arriving here.
6582void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6583 std::string StubEnc) {
6584 if (!ID)
6585 return;
6586 Entry &E = Map[ID];
6587 assert( (E.Str.empty() || E.State == Recursive) &&
6588 "Incorrectly use of addIncomplete");
6589 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6590 E.Swapped.swap(E.Str); // swap out the Recursive
6591 E.Str.swap(StubEnc);
6592 E.State = Incomplete;
6593 ++IncompleteCount;
6594}
6595
6596/// Once the RecordType has been expanded, the temporary incomplete TypeString
6597/// must be removed from the cache.
6598/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6599/// Returns true if the RecordType was defined recursively.
6600bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6601 if (!ID)
6602 return false;
6603 auto I = Map.find(ID);
6604 assert(I != Map.end() && "Entry not present");
6605 Entry &E = I->second;
6606 assert( (E.State == Incomplete ||
6607 E.State == IncompleteUsed) &&
6608 "Entry must be an incomplete type");
6609 bool IsRecursive = false;
6610 if (E.State == IncompleteUsed) {
6611 // We made use of our Incomplete encoding, thus we are recursive.
6612 IsRecursive = true;
6613 --IncompleteUsedCount;
6614 }
6615 if (E.Swapped.empty())
6616 Map.erase(I);
6617 else {
6618 // Swap the Recursive back.
6619 E.Swapped.swap(E.Str);
6620 E.Swapped.clear();
6621 E.State = Recursive;
6622 }
6623 --IncompleteCount;
6624 return IsRecursive;
6625}
6626
6627/// Add the encoded TypeString to the cache only if it is NonRecursive or
6628/// Recursive (viz: all sub-members were expanded as fully as possible).
6629void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6630 bool IsRecursive) {
6631 if (!ID || IncompleteUsedCount)
6632 return; // No key or it is is an incomplete sub-type so don't add.
6633 Entry &E = Map[ID];
6634 if (IsRecursive && !E.Str.empty()) {
6635 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6636 "This is not the same Recursive entry");
6637 // The parent container was not recursive after all, so we could have used
6638 // this Recursive sub-member entry after all, but we assumed the worse when
6639 // we started viz: IncompleteCount!=0.
6640 return;
6641 }
6642 assert(E.Str.empty() && "Entry already present");
6643 E.Str = Str.str();
6644 E.State = IsRecursive? Recursive : NonRecursive;
6645}
6646
6647/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6648/// are recursively expanding a type (IncompleteCount != 0) and the cached
6649/// encoding is Recursive, return an empty StringRef.
6650StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6651 if (!ID)
6652 return StringRef(); // We have no key.
6653 auto I = Map.find(ID);
6654 if (I == Map.end())
6655 return StringRef(); // We have no encoding.
6656 Entry &E = I->second;
6657 if (E.State == Recursive && IncompleteCount)
6658 return StringRef(); // We don't use Recursive encodings for member types.
6659
6660 if (E.State == Incomplete) {
6661 // The incomplete type is being used to break out of recursion.
6662 E.State = IncompleteUsed;
6663 ++IncompleteUsedCount;
6664 }
6665 return E.Str.c_str();
6666}
6667
6668/// The XCore ABI includes a type information section that communicates symbol
6669/// type information to the linker. The linker uses this information to verify
6670/// safety/correctness of things such as array bound and pointers et al.
6671/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6672/// This type information (TypeString) is emitted into meta data for all global
6673/// symbols: definitions, declarations, functions & variables.
6674///
6675/// The TypeString carries type, qualifier, name, size & value details.
6676/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6677/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6678/// The output is tested by test/CodeGen/xcore-stringtype.c.
6679///
6680static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6681 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6682
6683/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6684void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6685 CodeGen::CodeGenModule &CGM) const {
6686 SmallStringEnc Enc;
6687 if (getTypeString(Enc, D, CGM, TSC)) {
6688 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006689 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6690 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006691 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6692 llvm::NamedMDNode *MD =
6693 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6694 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6695 }
6696}
6697
6698static bool appendType(SmallStringEnc &Enc, QualType QType,
6699 const CodeGen::CodeGenModule &CGM,
6700 TypeStringCache &TSC);
6701
6702/// Helper function for appendRecordType().
6703/// Builds a SmallVector containing the encoded field types in declaration order.
6704static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6705 const RecordDecl *RD,
6706 const CodeGen::CodeGenModule &CGM,
6707 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006708 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006709 SmallStringEnc Enc;
6710 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006711 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006712 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006713 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006714 Enc += "b(";
6715 llvm::raw_svector_ostream OS(Enc);
6716 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006717 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006718 OS.flush();
6719 Enc += ':';
6720 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006721 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006722 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006723 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006724 Enc += ')';
6725 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006726 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006727 }
6728 return true;
6729}
6730
6731/// Appends structure and union types to Enc and adds encoding to cache.
6732/// Recursively calls appendType (via extractFieldType) for each field.
6733/// Union types have their fields ordered according to the ABI.
6734static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6735 const CodeGen::CodeGenModule &CGM,
6736 TypeStringCache &TSC, const IdentifierInfo *ID) {
6737 // Append the cached TypeString if we have one.
6738 StringRef TypeString = TSC.lookupStr(ID);
6739 if (!TypeString.empty()) {
6740 Enc += TypeString;
6741 return true;
6742 }
6743
6744 // Start to emit an incomplete TypeString.
6745 size_t Start = Enc.size();
6746 Enc += (RT->isUnionType()? 'u' : 's');
6747 Enc += '(';
6748 if (ID)
6749 Enc += ID->getName();
6750 Enc += "){";
6751
6752 // We collect all encoded fields and order as necessary.
6753 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006754 const RecordDecl *RD = RT->getDecl()->getDefinition();
6755 if (RD && !RD->field_empty()) {
6756 // An incomplete TypeString stub is placed in the cache for this RecordType
6757 // so that recursive calls to this RecordType will use it whilst building a
6758 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006759 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006760 std::string StubEnc(Enc.substr(Start).str());
6761 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6762 TSC.addIncomplete(ID, std::move(StubEnc));
6763 if (!extractFieldType(FE, RD, CGM, TSC)) {
6764 (void) TSC.removeIncomplete(ID);
6765 return false;
6766 }
6767 IsRecursive = TSC.removeIncomplete(ID);
6768 // The ABI requires unions to be sorted but not structures.
6769 // See FieldEncoding::operator< for sort algorithm.
6770 if (RT->isUnionType())
6771 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006772 // We can now complete the TypeString.
6773 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006774 for (unsigned I = 0; I != E; ++I) {
6775 if (I)
6776 Enc += ',';
6777 Enc += FE[I].str();
6778 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006779 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006780 Enc += '}';
6781 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6782 return true;
6783}
6784
6785/// Appends enum types to Enc and adds the encoding to the cache.
6786static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6787 TypeStringCache &TSC,
6788 const IdentifierInfo *ID) {
6789 // Append the cached TypeString if we have one.
6790 StringRef TypeString = TSC.lookupStr(ID);
6791 if (!TypeString.empty()) {
6792 Enc += TypeString;
6793 return true;
6794 }
6795
6796 size_t Start = Enc.size();
6797 Enc += "e(";
6798 if (ID)
6799 Enc += ID->getName();
6800 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006801
6802 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006803 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006804 SmallVector<FieldEncoding, 16> FE;
6805 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6806 ++I) {
6807 SmallStringEnc EnumEnc;
6808 EnumEnc += "m(";
6809 EnumEnc += I->getName();
6810 EnumEnc += "){";
6811 I->getInitVal().toString(EnumEnc);
6812 EnumEnc += '}';
6813 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6814 }
6815 std::sort(FE.begin(), FE.end());
6816 unsigned E = FE.size();
6817 for (unsigned I = 0; I != E; ++I) {
6818 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006819 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006820 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006821 }
6822 }
6823 Enc += '}';
6824 TSC.addIfComplete(ID, Enc.substr(Start), false);
6825 return true;
6826}
6827
6828/// Appends type's qualifier to Enc.
6829/// This is done prior to appending the type's encoding.
6830static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6831 // Qualifiers are emitted in alphabetical order.
6832 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6833 int Lookup = 0;
6834 if (QT.isConstQualified())
6835 Lookup += 1<<0;
6836 if (QT.isRestrictQualified())
6837 Lookup += 1<<1;
6838 if (QT.isVolatileQualified())
6839 Lookup += 1<<2;
6840 Enc += Table[Lookup];
6841}
6842
6843/// Appends built-in types to Enc.
6844static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6845 const char *EncType;
6846 switch (BT->getKind()) {
6847 case BuiltinType::Void:
6848 EncType = "0";
6849 break;
6850 case BuiltinType::Bool:
6851 EncType = "b";
6852 break;
6853 case BuiltinType::Char_U:
6854 EncType = "uc";
6855 break;
6856 case BuiltinType::UChar:
6857 EncType = "uc";
6858 break;
6859 case BuiltinType::SChar:
6860 EncType = "sc";
6861 break;
6862 case BuiltinType::UShort:
6863 EncType = "us";
6864 break;
6865 case BuiltinType::Short:
6866 EncType = "ss";
6867 break;
6868 case BuiltinType::UInt:
6869 EncType = "ui";
6870 break;
6871 case BuiltinType::Int:
6872 EncType = "si";
6873 break;
6874 case BuiltinType::ULong:
6875 EncType = "ul";
6876 break;
6877 case BuiltinType::Long:
6878 EncType = "sl";
6879 break;
6880 case BuiltinType::ULongLong:
6881 EncType = "ull";
6882 break;
6883 case BuiltinType::LongLong:
6884 EncType = "sll";
6885 break;
6886 case BuiltinType::Float:
6887 EncType = "ft";
6888 break;
6889 case BuiltinType::Double:
6890 EncType = "d";
6891 break;
6892 case BuiltinType::LongDouble:
6893 EncType = "ld";
6894 break;
6895 default:
6896 return false;
6897 }
6898 Enc += EncType;
6899 return true;
6900}
6901
6902/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6903static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6904 const CodeGen::CodeGenModule &CGM,
6905 TypeStringCache &TSC) {
6906 Enc += "p(";
6907 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6908 return false;
6909 Enc += ')';
6910 return true;
6911}
6912
6913/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006914static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6915 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006916 const CodeGen::CodeGenModule &CGM,
6917 TypeStringCache &TSC, StringRef NoSizeEnc) {
6918 if (AT->getSizeModifier() != ArrayType::Normal)
6919 return false;
6920 Enc += "a(";
6921 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6922 CAT->getSize().toStringUnsigned(Enc);
6923 else
6924 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6925 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006926 // The Qualifiers should be attached to the type rather than the array.
6927 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006928 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6929 return false;
6930 Enc += ')';
6931 return true;
6932}
6933
6934/// Appends a function encoding to Enc, calling appendType for the return type
6935/// and the arguments.
6936static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6937 const CodeGen::CodeGenModule &CGM,
6938 TypeStringCache &TSC) {
6939 Enc += "f{";
6940 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6941 return false;
6942 Enc += "}(";
6943 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6944 // N.B. we are only interested in the adjusted param types.
6945 auto I = FPT->param_type_begin();
6946 auto E = FPT->param_type_end();
6947 if (I != E) {
6948 do {
6949 if (!appendType(Enc, *I, CGM, TSC))
6950 return false;
6951 ++I;
6952 if (I != E)
6953 Enc += ',';
6954 } while (I != E);
6955 if (FPT->isVariadic())
6956 Enc += ",va";
6957 } else {
6958 if (FPT->isVariadic())
6959 Enc += "va";
6960 else
6961 Enc += '0';
6962 }
6963 }
6964 Enc += ')';
6965 return true;
6966}
6967
6968/// Handles the type's qualifier before dispatching a call to handle specific
6969/// type encodings.
6970static bool appendType(SmallStringEnc &Enc, QualType QType,
6971 const CodeGen::CodeGenModule &CGM,
6972 TypeStringCache &TSC) {
6973
6974 QualType QT = QType.getCanonicalType();
6975
Robert Lytton6adb20f2014-06-05 09:06:21 +00006976 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6977 // The Qualifiers should be attached to the type rather than the array.
6978 // Thus we don't call appendQualifier() here.
6979 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6980
Robert Lytton844aeeb2014-05-02 09:33:20 +00006981 appendQualifier(Enc, QT);
6982
6983 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6984 return appendBuiltinType(Enc, BT);
6985
Robert Lytton844aeeb2014-05-02 09:33:20 +00006986 if (const PointerType *PT = QT->getAs<PointerType>())
6987 return appendPointerType(Enc, PT, CGM, TSC);
6988
6989 if (const EnumType *ET = QT->getAs<EnumType>())
6990 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6991
6992 if (const RecordType *RT = QT->getAsStructureType())
6993 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6994
6995 if (const RecordType *RT = QT->getAsUnionType())
6996 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6997
6998 if (const FunctionType *FT = QT->getAs<FunctionType>())
6999 return appendFunctionType(Enc, FT, CGM, TSC);
7000
7001 return false;
7002}
7003
7004static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7005 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7006 if (!D)
7007 return false;
7008
7009 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7010 if (FD->getLanguageLinkage() != CLanguageLinkage)
7011 return false;
7012 return appendType(Enc, FD->getType(), CGM, TSC);
7013 }
7014
7015 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7016 if (VD->getLanguageLinkage() != CLanguageLinkage)
7017 return false;
7018 QualType QT = VD->getType().getCanonicalType();
7019 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7020 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007021 // The Qualifiers should be attached to the type rather than the array.
7022 // Thus we don't call appendQualifier() here.
7023 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007024 }
7025 return appendType(Enc, QT, CGM, TSC);
7026 }
7027 return false;
7028}
7029
7030
Robert Lytton0e076492013-08-13 09:43:10 +00007031//===----------------------------------------------------------------------===//
7032// Driver code
7033//===----------------------------------------------------------------------===//
7034
Rafael Espindola9f834732014-09-19 01:54:22 +00007035const llvm::Triple &CodeGenModule::getTriple() const {
7036 return getTarget().getTriple();
7037}
7038
7039bool CodeGenModule::supportsCOMDAT() const {
7040 return !getTriple().isOSBinFormatMachO();
7041}
7042
Chris Lattner2b037972010-07-29 02:01:43 +00007043const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007044 if (TheTargetCodeGenInfo)
7045 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007046
John McCallc8e01702013-04-16 22:48:15 +00007047 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007048 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007049 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007050 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007051
Derek Schuff09338a22012-09-06 17:37:28 +00007052 case llvm::Triple::le32:
7053 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007054 case llvm::Triple::mips:
7055 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007056 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7057
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007058 case llvm::Triple::mips64:
7059 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007060 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7061
Tim Northover25e8a672014-05-24 12:51:25 +00007062 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007063 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007064 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007065 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007066 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007067
Tim Northover573cbee2014-05-24 12:52:07 +00007068 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007069 }
7070
Daniel Dunbard59655c2009-09-12 00:59:49 +00007071 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007072 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007073 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007074 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007075 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007076 if (Triple.getOS() == llvm::Triple::Win32) {
7077 TheTargetCodeGenInfo =
7078 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7079 return *TheTargetCodeGenInfo;
7080 }
7081
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007082 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007083 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007084 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007085 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007086 (CodeGenOpts.FloatABI != "soft" &&
7087 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007088 Kind = ARMABIInfo::AAPCS_VFP;
7089
Derek Schuff71658bd2015-01-29 00:47:04 +00007090 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007091 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007092
John McCallea8d8bb2010-03-11 00:10:12 +00007093 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007094 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007095 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007096 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007097 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007098 if (getTarget().getABI() == "elfv2")
7099 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007100 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007101
Ulrich Weigandb7122372014-07-21 00:48:09 +00007102 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007103 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007104 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007105 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007106 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007107 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007108 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007109 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007110 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007111 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007112
Ulrich Weigandb7122372014-07-21 00:48:09 +00007113 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007114 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007115 }
John McCallea8d8bb2010-03-11 00:10:12 +00007116
Peter Collingbournec947aae2012-05-20 23:28:41 +00007117 case llvm::Triple::nvptx:
7118 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007119 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007120
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007121 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007122 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007123
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007124 case llvm::Triple::systemz: {
7125 bool HasVector = getTarget().getABI() == "vector";
7126 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7127 HasVector));
7128 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007129
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007130 case llvm::Triple::tce:
7131 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7132
Eli Friedman33465822011-07-08 23:31:17 +00007133 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007134 bool IsDarwinVectorABI = Triple.isOSDarwin();
7135 bool IsSmallStructInRegABI =
7136 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007137 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007138
John McCall1fe2a8c2013-06-18 02:46:29 +00007139 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007140 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007141 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007142 IsDarwinVectorABI, IsSmallStructInRegABI,
7143 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007144 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007145 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007146 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007147 new X86_32TargetCodeGenInfo(Types,
7148 IsDarwinVectorABI, IsSmallStructInRegABI,
7149 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007150 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007151 }
Eli Friedman33465822011-07-08 23:31:17 +00007152 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007153
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007154 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007155 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007156
Chris Lattner04dc9572010-08-31 16:44:54 +00007157 switch (Triple.getOS()) {
7158 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007159 return *(TheTargetCodeGenInfo =
7160 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007161 case llvm::Triple::PS4:
7162 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007163 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007164 return *(TheTargetCodeGenInfo =
7165 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007166 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007167 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007168 case llvm::Triple::hexagon:
7169 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007170 case llvm::Triple::r600:
7171 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007172 case llvm::Triple::amdgcn:
7173 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007174 case llvm::Triple::sparcv9:
7175 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007176 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007177 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007178 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007179}