blob: e97b33a54e894b7bd9a8d5a2490ecacb99b350a7 [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
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000111bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
112 return false;
113}
114
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000115void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000117 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000118 switch (TheKind) {
119 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000120 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000122 Ty->print(OS);
123 else
124 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000125 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000126 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000127 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000128 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000129 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000130 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000132 case InAlloca:
133 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
134 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000135 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000136 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000137 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000138 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000139 break;
140 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000141 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000142 break;
143 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000144 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000145}
146
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000147TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
148
John McCall3480ef22011-08-30 01:42:09 +0000149// If someone can figure out a general rule for this, that would be great.
150// It's probably just doomed to be platform-dependent, though.
151unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
152 // Verified for:
153 // x86-64 FreeBSD, Linux, Darwin
154 // x86-32 FreeBSD, Linux, Darwin
155 // PowerPC Linux, Darwin
156 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000157 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000158 return 32;
159}
160
John McCalla729c622012-02-17 03:33:10 +0000161bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
162 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000163 // The following conventions are known to require this to be false:
164 // x86_stdcall
165 // MIPS
166 // For everything else, we just prefer false unless we opt out.
167 return false;
168}
169
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000170void
171TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
172 llvm::SmallString<24> &Opt) const {
173 // This assumes the user is passing a library name like "rt" instead of a
174 // filename like "librt.a/so", and that they don't care whether it's static or
175 // dynamic.
176 Opt = "-l";
177 Opt += Lib;
178}
179
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000180static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000181
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000182/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000183/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
185 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186 if (FD->isUnnamedBitfield())
187 return true;
188
189 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000190
Eli Friedman0b3f2012011-11-18 03:47:20 +0000191 // Constant arrays of empty records count as empty, strip them off.
192 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000194 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
195 if (AT->getSize() == 0)
196 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000197 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000198 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000200 const RecordType *RT = FT->getAs<RecordType>();
201 if (!RT)
202 return false;
203
204 // C++ record fields are never empty, at least in the Itanium ABI.
205 //
206 // FIXME: We should use a predicate for whether this behavior is true in the
207 // current ABI.
208 if (isa<CXXRecordDecl>(RT->getDecl()))
209 return false;
210
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000211 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000212}
213
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000214/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215/// fields. Note that a structure with a flexible array member is not
216/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000217static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000218 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000219 if (!RT)
220 return 0;
221 const RecordDecl *RD = RT->getDecl();
222 if (RD->hasFlexibleArrayMember())
223 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000224
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000225 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000226 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000227 for (const auto &I : CXXRD->bases())
228 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000229 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000230
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000231 for (const auto *I : RD->fields())
232 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 return false;
234 return true;
235}
236
237/// isSingleElementStruct - Determine if a structure is a "single
238/// element struct", i.e. it has exactly one non-empty field or
239/// exactly one field which is itself a single element
240/// struct. Structures with flexible array members are never
241/// considered single element structs.
242///
243/// \return The field declaration for the single non-empty field, if
244/// it exists.
245static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000246 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000247 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000248 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249
250 const RecordDecl *RD = RT->getDecl();
251 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000252 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000253
Craig Topper8a13c412014-05-21 05:09:00 +0000254 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000255
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000256 // If this is a C++ record, check the bases first.
257 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000258 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000259 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000260 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000261 continue;
262
263 // If we already found an element then this isn't a single-element struct.
264 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000265 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000266
267 // If this is non-empty and not a single element struct, the composite
268 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000269 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000270 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000271 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000272 }
273 }
274
275 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000276 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000277 QualType FT = FD->getType();
278
279 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000280 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000281 continue;
282
283 // If we already found an element then this isn't a single-element
284 // struct.
285 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000286 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000287
288 // Treat single element arrays as the element.
289 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
290 if (AT->getSize().getZExtValue() != 1)
291 break;
292 FT = AT->getElementType();
293 }
294
John McCalla1dee5302010-08-22 10:59:02 +0000295 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 Found = FT.getTypePtr();
297 } else {
298 Found = isSingleElementStruct(FT, Context);
299 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000300 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000301 }
302 }
303
Eli Friedmanee945342011-11-18 01:25:50 +0000304 // We don't consider a struct a single-element struct if it has
305 // padding beyond the element type.
306 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000307 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000308
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000309 return Found;
310}
311
312static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000313 // Treat complex types as the element type.
314 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
315 Ty = CTy->getElementType();
316
317 // Check for a type which we know has a simple scalar argument-passing
318 // convention without any padding. (We're specifically looking for 32
319 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000320 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000321 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000322 return false;
323
324 uint64_t Size = Context.getTypeSize(Ty);
325 return Size == 32 || Size == 64;
326}
327
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000328/// canExpandIndirectArgument - Test whether an argument type which is to be
329/// passed indirectly (on the stack) would have the equivalent layout if it was
330/// expanded into separate arguments. If so, we prefer to do the latter to avoid
331/// inhibiting optimizations.
332///
333// FIXME: This predicate is missing many cases, currently it just follows
334// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
335// should probably make this smarter, or better yet make the LLVM backend
336// capable of handling it.
337static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
338 // We can only expand structure types.
339 const RecordType *RT = Ty->getAs<RecordType>();
340 if (!RT)
341 return false;
342
343 // We can only expand (C) structures.
344 //
345 // FIXME: This needs to be generalized to handle classes as well.
346 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000347 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000348 return false;
349
Manman Ren27382782015-04-03 18:10:29 +0000350 // We try to expand CLike CXXRecordDecl.
351 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
352 if (!CXXRD->isCLike())
353 return false;
354 }
355
Eli Friedmane5c85622011-11-18 01:32:26 +0000356 uint64_t Size = 0;
357
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000358 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359 if (!is32Or64BitBasicType(FD->getType(), Context))
360 return false;
361
362 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
363 // how to expand them yet, and the predicate for telling if a bitfield still
364 // counts as "basic" is more complicated than what we were doing previously.
365 if (FD->isBitField())
366 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000367
368 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000369 }
370
Eli Friedmane5c85622011-11-18 01:32:26 +0000371 // Make sure there are not any holes in the struct.
372 if (Size != Context.getTypeSize(Ty))
373 return false;
374
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375 return true;
376}
377
378namespace {
379/// DefaultABIInfo - The default implementation for ABI specific
380/// details. This implementation provides information which results in
381/// self-consistent and sensible LLVM IR generation, but does not
382/// conform to any particular ABI.
383class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000384public:
385 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000386
Chris Lattner458b2aa2010-07-29 02:16:43 +0000387 ABIArgInfo classifyReturnType(QualType RetTy) const;
388 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000389
Craig Topper4f12f102014-03-12 06:41:41 +0000390 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000391 if (!getCXXABI().classifyReturnType(FI))
392 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000393 for (auto &I : FI.arguments())
394 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000395 }
396
Craig Topper4f12f102014-03-12 06:41:41 +0000397 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
398 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000399};
400
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000401class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
402public:
Chris Lattner2b037972010-07-29 02:01:43 +0000403 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
404 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000405};
406
407llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
408 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000409 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000410}
411
Chris Lattner458b2aa2010-07-29 02:16:43 +0000412ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000413 Ty = useFirstFieldIfTransparentUnion(Ty);
414
415 if (isAggregateTypeForABI(Ty)) {
416 // Records with non-trivial destructors/copy-constructors should not be
417 // passed by value.
418 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
419 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
420
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000421 return ABIArgInfo::getIndirect(0);
Reid Klecknerac385062015-05-18 22:46:30 +0000422 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000423
Chris Lattner9723d6c2010-03-11 18:19:55 +0000424 // Treat an enum type as its underlying type.
425 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
426 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000427
Chris Lattner9723d6c2010-03-11 18:19:55 +0000428 return (Ty->isPromotableIntegerType() ?
429 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000430}
431
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000432ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
433 if (RetTy->isVoidType())
434 return ABIArgInfo::getIgnore();
435
436 if (isAggregateTypeForABI(RetTy))
437 return ABIArgInfo::getIndirect(0);
438
439 // Treat an enum type as its underlying type.
440 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
441 RetTy = EnumTy->getDecl()->getIntegerType();
442
443 return (RetTy->isPromotableIntegerType() ?
444 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
445}
446
Derek Schuff09338a22012-09-06 17:37:28 +0000447//===----------------------------------------------------------------------===//
448// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000449//
450// This is a simplified version of the x86_32 ABI. Arguments and return values
451// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000452//===----------------------------------------------------------------------===//
453
454class PNaClABIInfo : public ABIInfo {
455 public:
456 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
457
458 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000460
Craig Topper4f12f102014-03-12 06:41:41 +0000461 void computeInfo(CGFunctionInfo &FI) const override;
462 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000464};
465
466class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
467 public:
468 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
469 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
470};
471
472void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000473 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000474 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
475
Reid Kleckner40ca9132014-05-13 22:05:45 +0000476 for (auto &I : FI.arguments())
477 I.info = classifyArgumentType(I.type);
478}
Derek Schuff09338a22012-09-06 17:37:28 +0000479
480llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
481 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000482 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000483}
484
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000485/// \brief Classify argument of given type \p Ty.
486ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000487 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000488 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000489 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000490 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000491 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
492 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000493 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000494 } else if (Ty->isFloatingType()) {
495 // Floating-point types don't go inreg.
496 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000497 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000498
499 return (Ty->isPromotableIntegerType() ?
500 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000501}
502
503ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
504 if (RetTy->isVoidType())
505 return ABIArgInfo::getIgnore();
506
Eli Benderskye20dad62013-04-04 22:49:35 +0000507 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000508 if (isAggregateTypeForABI(RetTy))
509 return ABIArgInfo::getIndirect(0);
510
511 // Treat an enum type as its underlying type.
512 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
513 RetTy = EnumTy->getDecl()->getIntegerType();
514
515 return (RetTy->isPromotableIntegerType() ?
516 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
517}
518
Chad Rosier651c1832013-03-25 21:00:27 +0000519/// IsX86_MMXType - Return true if this is an MMX type.
520bool IsX86_MMXType(llvm::Type *IRType) {
521 // 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 +0000522 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
523 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
524 IRType->getScalarSizeInBits() != 64;
525}
526
Jay Foad7c57be32011-07-11 09:56:20 +0000527static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000529 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000530 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
531 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
532 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000533 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000534 }
535
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000536 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000537 }
538
539 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000540 return Ty;
541}
542
Reid Kleckner80944df2014-10-31 22:00:51 +0000543/// Returns true if this type can be passed in SSE registers with the
544/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
545static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
546 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
547 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
548 return true;
549 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
550 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
551 // registers specially.
552 unsigned VecSize = Context.getTypeSize(VT);
553 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
554 return true;
555 }
556 return false;
557}
558
559/// Returns true if this aggregate is small enough to be passed in SSE registers
560/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
561static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
562 return NumMembers <= 4;
563}
564
Chris Lattner0cf24192010-06-28 20:05:43 +0000565//===----------------------------------------------------------------------===//
566// X86-32 ABI Implementation
567//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000568
Reid Kleckner661f35b2014-01-18 01:12:41 +0000569/// \brief Similar to llvm::CCState, but for Clang.
570struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000571 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000572
573 unsigned CC;
574 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000575 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000576};
577
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578/// X86_32ABIInfo - The X86-32 ABI information.
579class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000580 enum Class {
581 Integer,
582 Float
583 };
584
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000585 static const unsigned MinABIStackAlignInBytes = 4;
586
David Chisnallde3a0692009-08-17 23:08:21 +0000587 bool IsDarwinVectorABI;
588 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000589 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000590 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000591
592 static bool isRegisterSize(unsigned Size) {
593 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
594 }
595
Reid Kleckner80944df2014-10-31 22:00:51 +0000596 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
597 // FIXME: Assumes vectorcall is in use.
598 return isX86VectorTypeForVectorCall(getContext(), Ty);
599 }
600
601 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
602 uint64_t NumMembers) const override {
603 // FIXME: Assumes vectorcall is in use.
604 return isX86VectorCallAggregateSmallEnough(NumMembers);
605 }
606
Reid Kleckner40ca9132014-05-13 22:05:45 +0000607 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000608
Daniel Dunbar557893d2010-04-21 19:10:51 +0000609 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
610 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000611 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
612
613 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000614
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000615 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000616 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000617
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000618 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000619 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000620 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
621 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000623 /// \brief Rewrite the function info so that all memory arguments use
624 /// inalloca.
625 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
626
627 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
628 unsigned &StackOffset, ABIArgInfo &Info,
629 QualType Type) const;
630
Rafael Espindola75419dc2012-07-23 23:30:29 +0000631public:
632
Craig Topper4f12f102014-03-12 06:41:41 +0000633 void computeInfo(CGFunctionInfo &FI) const override;
634 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
635 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000636
Chad Rosier651c1832013-03-25 21:00:27 +0000637 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000638 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000639 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000640 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000641};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000642
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000643class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
644public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000645 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000646 bool d, bool p, bool w, unsigned r)
647 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000648
John McCall1fe2a8c2013-06-18 02:46:29 +0000649 static bool isStructReturnInRegABI(
650 const llvm::Triple &Triple, const CodeGenOptions &Opts);
651
Eric Christopher162c91c2015-06-05 22:03:00 +0000652 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000653 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000654
Craig Topper4f12f102014-03-12 06:41:41 +0000655 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000656 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000657 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000658 return 4;
659 }
660
661 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000662 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000663
Jay Foad7c57be32011-07-11 09:56:20 +0000664 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000665 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000666 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000667 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
668 }
669
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000670 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
671 std::string &Constraints,
672 std::vector<llvm::Type *> &ResultRegTypes,
673 std::vector<llvm::Type *> &ResultTruncRegTypes,
674 std::vector<LValue> &ResultRegDests,
675 std::string &AsmString,
676 unsigned NumOutputs) const override;
677
Craig Topper4f12f102014-03-12 06:41:41 +0000678 llvm::Constant *
679 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000680 unsigned Sig = (0xeb << 0) | // jmp rel8
681 (0x06 << 8) | // .+0x08
682 ('F' << 16) |
683 ('T' << 24);
684 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
685 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000686};
687
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000688}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000689
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000690/// Rewrite input constraint references after adding some output constraints.
691/// In the case where there is one output and one input and we add one output,
692/// we need to replace all operand references greater than or equal to 1:
693/// mov $0, $1
694/// mov eax, $1
695/// The result will be:
696/// mov $0, $2
697/// mov eax, $2
698static void rewriteInputConstraintReferences(unsigned FirstIn,
699 unsigned NumNewOuts,
700 std::string &AsmString) {
701 std::string Buf;
702 llvm::raw_string_ostream OS(Buf);
703 size_t Pos = 0;
704 while (Pos < AsmString.size()) {
705 size_t DollarStart = AsmString.find('$', Pos);
706 if (DollarStart == std::string::npos)
707 DollarStart = AsmString.size();
708 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
709 if (DollarEnd == std::string::npos)
710 DollarEnd = AsmString.size();
711 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
712 Pos = DollarEnd;
713 size_t NumDollars = DollarEnd - DollarStart;
714 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
715 // We have an operand reference.
716 size_t DigitStart = Pos;
717 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
718 if (DigitEnd == std::string::npos)
719 DigitEnd = AsmString.size();
720 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
721 unsigned OperandIndex;
722 if (!OperandStr.getAsInteger(10, OperandIndex)) {
723 if (OperandIndex >= FirstIn)
724 OperandIndex += NumNewOuts;
725 OS << OperandIndex;
726 } else {
727 OS << OperandStr;
728 }
729 Pos = DigitEnd;
730 }
731 }
732 AsmString = std::move(OS.str());
733}
734
735/// Add output constraints for EAX:EDX because they are return registers.
736void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
737 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
738 std::vector<llvm::Type *> &ResultRegTypes,
739 std::vector<llvm::Type *> &ResultTruncRegTypes,
740 std::vector<LValue> &ResultRegDests, std::string &AsmString,
741 unsigned NumOutputs) const {
742 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
743
744 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
745 // larger.
746 if (!Constraints.empty())
747 Constraints += ',';
748 if (RetWidth <= 32) {
749 Constraints += "={eax}";
750 ResultRegTypes.push_back(CGF.Int32Ty);
751 } else {
752 // Use the 'A' constraint for EAX:EDX.
753 Constraints += "=A";
754 ResultRegTypes.push_back(CGF.Int64Ty);
755 }
756
757 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
758 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
759 ResultTruncRegTypes.push_back(CoerceTy);
760
761 // Coerce the integer by bitcasting the return slot pointer.
762 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
763 CoerceTy->getPointerTo()));
764 ResultRegDests.push_back(ReturnSlot);
765
766 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
767}
768
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000769/// shouldReturnTypeInRegister - Determine if the given type should be
770/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000771bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
772 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000773 uint64_t Size = Context.getTypeSize(Ty);
774
775 // Type must be register sized.
776 if (!isRegisterSize(Size))
777 return false;
778
779 if (Ty->isVectorType()) {
780 // 64- and 128- bit vectors inside structures are not returned in
781 // registers.
782 if (Size == 64 || Size == 128)
783 return false;
784
785 return true;
786 }
787
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000788 // If this is a builtin, pointer, enum, complex type, member pointer, or
789 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000790 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000791 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000792 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000793 return true;
794
795 // Arrays are treated like records.
796 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000797 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798
799 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000800 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801 if (!RT) return false;
802
Anders Carlsson40446e82010-01-27 03:25:19 +0000803 // FIXME: Traverse bases here too.
804
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000805 // Structure types are passed in register if all fields would be
806 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000807 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000808 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000809 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000810 continue;
811
812 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000813 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814 return false;
815 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000816 return true;
817}
818
Reid Kleckner661f35b2014-01-18 01:12:41 +0000819ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
820 // If the return value is indirect, then the hidden argument is consuming one
821 // integer register.
822 if (State.FreeRegs) {
823 --State.FreeRegs;
824 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
825 }
826 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
827}
828
Eric Christopher7565e0d2015-05-29 23:09:49 +0000829ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
830 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000831 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000832 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000833
Reid Kleckner80944df2014-10-31 22:00:51 +0000834 const Type *Base = nullptr;
835 uint64_t NumElts = 0;
836 if (State.CC == llvm::CallingConv::X86_VectorCall &&
837 isHomogeneousAggregate(RetTy, Base, NumElts)) {
838 // The LLVM struct type for such an aggregate should lower properly.
839 return ABIArgInfo::getDirect();
840 }
841
Chris Lattner458b2aa2010-07-29 02:16:43 +0000842 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000843 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000844 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000845 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000846
847 // 128-bit vectors are a special case; they are returned in
848 // registers and we need to make sure to pick a type the LLVM
849 // backend will like.
850 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000851 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000852 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000853
854 // Always return in register if it fits in a general purpose
855 // register, or if it is 64 bits and has a single element.
856 if ((Size == 8 || Size == 16 || Size == 32) ||
857 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000858 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000859 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000860
Reid Kleckner661f35b2014-01-18 01:12:41 +0000861 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000862 }
863
864 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000865 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000866
John McCalla1dee5302010-08-22 10:59:02 +0000867 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000868 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000869 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000870 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000872 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000873
David Chisnallde3a0692009-08-17 23:08:21 +0000874 // If specified, structs and unions are always indirect.
875 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000876 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000877
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000878 // Small structures which are register sized are generally returned
879 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000880 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000881 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000882
883 // As a special-case, if the struct is a "single-element" struct, and
884 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000885 // floating-point register. (MSVC does not apply this special case.)
886 // We apply a similar transformation for pointer types to improve the
887 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000888 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000889 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000890 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000891 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
892
893 // FIXME: We should be able to narrow this integer in cases with dead
894 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000895 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000896 }
897
Reid Kleckner661f35b2014-01-18 01:12:41 +0000898 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000899 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000900
Chris Lattner458b2aa2010-07-29 02:16:43 +0000901 // Treat an enum type as its underlying type.
902 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
903 RetTy = EnumTy->getDecl()->getIntegerType();
904
905 return (RetTy->isPromotableIntegerType() ?
906 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000907}
908
Eli Friedman7919bea2012-06-05 19:40:46 +0000909static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
910 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
911}
912
Daniel Dunbared23de32010-09-16 20:42:00 +0000913static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
914 const RecordType *RT = Ty->getAs<RecordType>();
915 if (!RT)
916 return 0;
917 const RecordDecl *RD = RT->getDecl();
918
919 // If this is a C++ record, check the bases first.
920 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000921 for (const auto &I : CXXRD->bases())
922 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000923 return false;
924
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000925 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000926 QualType FT = i->getType();
927
Eli Friedman7919bea2012-06-05 19:40:46 +0000928 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000929 return true;
930
931 if (isRecordWithSSEVectorType(Context, FT))
932 return true;
933 }
934
935 return false;
936}
937
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000938unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
939 unsigned Align) const {
940 // Otherwise, if the alignment is less than or equal to the minimum ABI
941 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000942 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000943 return 0; // Use default alignment.
944
945 // On non-Darwin, the stack type alignment is always 4.
946 if (!IsDarwinVectorABI) {
947 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000948 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000949 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000950
Daniel Dunbared23de32010-09-16 20:42:00 +0000951 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000952 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
953 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000954 return 16;
955
956 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000957}
958
Rafael Espindola703c47f2012-10-19 05:04:37 +0000959ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000960 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000961 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000962 if (State.FreeRegs) {
963 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000964 return ABIArgInfo::getIndirectInReg(0, false);
965 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000966 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000967 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000968
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000969 // Compute the byval alignment.
970 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
971 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
972 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000973 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000974
975 // If the stack alignment is less than the type alignment, realign the
976 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000977 bool Realign = TypeAlign > StackAlign;
978 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000979}
980
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000981X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
982 const Type *T = isSingleElementStruct(Ty, getContext());
983 if (!T)
984 T = Ty.getTypePtr();
985
986 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
987 BuiltinType::Kind K = BT->getKind();
988 if (K == BuiltinType::Float || K == BuiltinType::Double)
989 return Float;
990 }
991 return Integer;
992}
993
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
995 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000996 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000997 Class C = classify(Ty);
998 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000999 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001000
Rafael Espindola077dd592012-10-24 01:58:58 +00001001 unsigned Size = getContext().getTypeSize(Ty);
1002 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001003
1004 if (SizeInRegs == 0)
1005 return false;
1006
Reid Kleckner661f35b2014-01-18 01:12:41 +00001007 if (SizeInRegs > State.FreeRegs) {
1008 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001009 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001010 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001011
Reid Kleckner661f35b2014-01-18 01:12:41 +00001012 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001013
Reid Kleckner80944df2014-10-31 22:00:51 +00001014 if (State.CC == llvm::CallingConv::X86_FastCall ||
1015 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001016 if (Size > 32)
1017 return false;
1018
1019 if (Ty->isIntegralOrEnumerationType())
1020 return true;
1021
1022 if (Ty->isPointerType())
1023 return true;
1024
1025 if (Ty->isReferenceType())
1026 return true;
1027
Reid Kleckner661f35b2014-01-18 01:12:41 +00001028 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001029 NeedsPadding = true;
1030
Rafael Espindola077dd592012-10-24 01:58:58 +00001031 return false;
1032 }
1033
Rafael Espindola703c47f2012-10-19 05:04:37 +00001034 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001035}
1036
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001037ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1038 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001039 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001040
Reid Klecknerb1be6832014-11-15 01:41:41 +00001041 Ty = useFirstFieldIfTransparentUnion(Ty);
1042
Reid Kleckner80944df2014-10-31 22:00:51 +00001043 // Check with the C++ ABI first.
1044 const RecordType *RT = Ty->getAs<RecordType>();
1045 if (RT) {
1046 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1047 if (RAA == CGCXXABI::RAA_Indirect) {
1048 return getIndirectResult(Ty, false, State);
1049 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1050 // The field index doesn't matter, we'll fix it up later.
1051 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1052 }
1053 }
1054
1055 // vectorcall adds the concept of a homogenous vector aggregate, similar
1056 // to other targets.
1057 const Type *Base = nullptr;
1058 uint64_t NumElts = 0;
1059 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1060 isHomogeneousAggregate(Ty, Base, NumElts)) {
1061 if (State.FreeSSERegs >= NumElts) {
1062 State.FreeSSERegs -= NumElts;
1063 if (Ty->isBuiltinType() || Ty->isVectorType())
1064 return ABIArgInfo::getDirect();
1065 return ABIArgInfo::getExpand();
1066 }
1067 return getIndirectResult(Ty, /*ByVal=*/false, State);
1068 }
1069
1070 if (isAggregateTypeForABI(Ty)) {
1071 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001072 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001073 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001074 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001075
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001076 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001077 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001078 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001079 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001080
Eli Friedman9f061a32011-11-18 00:28:11 +00001081 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001082 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001083 return ABIArgInfo::getIgnore();
1084
Rafael Espindolafad28de2012-10-24 01:59:00 +00001085 llvm::LLVMContext &LLVMContext = getVMContext();
1086 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1087 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001088 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001089 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001090 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001091 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1092 return ABIArgInfo::getDirectInReg(Result);
1093 }
Craig Topper8a13c412014-05-21 05:09:00 +00001094 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001095
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001096 // Expand small (<= 128-bit) record types when we know that the stack layout
1097 // of those arguments will match the struct. This is important because the
1098 // LLVM backend isn't smart enough to remove byval, which inhibits many
1099 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001100 if (getContext().getTypeSize(Ty) <= 4*32 &&
1101 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001102 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001103 State.CC == llvm::CallingConv::X86_FastCall ||
1104 State.CC == llvm::CallingConv::X86_VectorCall,
1105 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106
Reid Kleckner661f35b2014-01-18 01:12:41 +00001107 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001108 }
1109
Chris Lattnerd774ae92010-08-26 20:05:13 +00001110 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001111 // On Darwin, some vectors are passed in memory, we handle this by passing
1112 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001113 if (IsDarwinVectorABI) {
1114 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001115 if ((Size == 8 || Size == 16 || Size == 32) ||
1116 (Size == 64 && VT->getNumElements() == 1))
1117 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1118 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001119 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001120
Chad Rosier651c1832013-03-25 21:00:27 +00001121 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1122 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001123
Chris Lattnerd774ae92010-08-26 20:05:13 +00001124 return ABIArgInfo::getDirect();
1125 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001126
1127
Chris Lattner458b2aa2010-07-29 02:16:43 +00001128 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1129 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001130
Rafael Espindolafad28de2012-10-24 01:59:00 +00001131 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001132 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001133
1134 if (Ty->isPromotableIntegerType()) {
1135 if (InReg)
1136 return ABIArgInfo::getExtendInReg();
1137 return ABIArgInfo::getExtend();
1138 }
1139 if (InReg)
1140 return ABIArgInfo::getDirectInReg();
1141 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001142}
1143
Rafael Espindolaa6472962012-07-24 00:01:07 +00001144void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001145 CCState State(FI.getCallingConvention());
1146 if (State.CC == llvm::CallingConv::X86_FastCall)
1147 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001148 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1149 State.FreeRegs = 2;
1150 State.FreeSSERegs = 6;
1151 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001152 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001153 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001154 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001155
Reid Kleckner677539d2014-07-10 01:58:55 +00001156 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001157 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001158 } else if (FI.getReturnInfo().isIndirect()) {
1159 // The C++ ABI is not aware of register usage, so we have to check if the
1160 // return value was sret and put it in a register ourselves if appropriate.
1161 if (State.FreeRegs) {
1162 --State.FreeRegs; // The sret parameter consumes a register.
1163 FI.getReturnInfo().setInReg(true);
1164 }
1165 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001166
Peter Collingbournef7706832014-12-12 23:41:25 +00001167 // The chain argument effectively gives us another free register.
1168 if (FI.isChainCall())
1169 ++State.FreeRegs;
1170
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001171 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001172 for (auto &I : FI.arguments()) {
1173 I.info = classifyArgumentType(I.type, State);
1174 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001175 }
1176
1177 // If we needed to use inalloca for any argument, do a second pass and rewrite
1178 // all the memory arguments to use inalloca.
1179 if (UsedInAlloca)
1180 rewriteWithInAlloca(FI);
1181}
1182
1183void
1184X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1185 unsigned &StackOffset,
1186 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001187 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1188 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1189 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1190 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1191
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001192 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1193 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001194 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001195 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001196 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001197 unsigned NumBytes = StackOffset - OldOffset;
1198 assert(NumBytes);
1199 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1200 Ty = llvm::ArrayType::get(Ty, NumBytes);
1201 FrameFields.push_back(Ty);
1202 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001203}
1204
Reid Kleckner852361d2014-07-26 00:12:26 +00001205static bool isArgInAlloca(const ABIArgInfo &Info) {
1206 // Leave ignored and inreg arguments alone.
1207 switch (Info.getKind()) {
1208 case ABIArgInfo::InAlloca:
1209 return true;
1210 case ABIArgInfo::Indirect:
1211 assert(Info.getIndirectByVal());
1212 return true;
1213 case ABIArgInfo::Ignore:
1214 return false;
1215 case ABIArgInfo::Direct:
1216 case ABIArgInfo::Extend:
1217 case ABIArgInfo::Expand:
1218 if (Info.getInReg())
1219 return false;
1220 return true;
1221 }
1222 llvm_unreachable("invalid enum");
1223}
1224
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001225void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1226 assert(IsWin32StructABI && "inalloca only supported on win32");
1227
1228 // Build a packed struct type for all of the arguments in memory.
1229 SmallVector<llvm::Type *, 6> FrameFields;
1230
1231 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001232 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1233
1234 // Put 'this' into the struct before 'sret', if necessary.
1235 bool IsThisCall =
1236 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1237 ABIArgInfo &Ret = FI.getReturnInfo();
1238 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1239 isArgInAlloca(I->info)) {
1240 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1241 ++I;
1242 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001243
1244 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001245 if (Ret.isIndirect() && !Ret.getInReg()) {
1246 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1247 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001248 // On Windows, the hidden sret parameter is always returned in eax.
1249 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001250 }
1251
1252 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001253 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001254 ++I;
1255
1256 // Put arguments passed in memory into the struct.
1257 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001258 if (isArgInAlloca(I->info))
1259 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001260 }
1261
1262 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1263 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001264}
1265
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001266llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1267 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001268 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269
1270 CGBuilderTy &Builder = CGF.Builder;
1271 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1272 "ap");
1273 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001274
1275 // Compute if the address needs to be aligned
1276 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1277 Align = getTypeStackAlignInBytes(Ty, Align);
1278 Align = std::max(Align, 4U);
1279 if (Align > 4) {
1280 // addr = (addr + align - 1) & -align;
1281 llvm::Value *Offset =
1282 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1283 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1284 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1285 CGF.Int32Ty);
1286 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1287 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1288 Addr->getType(),
1289 "ap.cur.aligned");
1290 }
1291
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001292 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001293 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001294 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1295
1296 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001297 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001298 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001299 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001300 "ap.next");
1301 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1302
1303 return AddrTyped;
1304}
1305
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001306bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1307 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1308 assert(Triple.getArch() == llvm::Triple::x86);
1309
1310 switch (Opts.getStructReturnConvention()) {
1311 case CodeGenOptions::SRCK_Default:
1312 break;
1313 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1314 return false;
1315 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1316 return true;
1317 }
1318
1319 if (Triple.isOSDarwin())
1320 return true;
1321
1322 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001323 case llvm::Triple::DragonFly:
1324 case llvm::Triple::FreeBSD:
1325 case llvm::Triple::OpenBSD:
1326 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001327 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001328 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001329 default:
1330 return false;
1331 }
1332}
1333
Eric Christopher162c91c2015-06-05 22:03:00 +00001334void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001335 llvm::GlobalValue *GV,
1336 CodeGen::CodeGenModule &CGM) const {
1337 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1338 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1339 // Get the LLVM function.
1340 llvm::Function *Fn = cast<llvm::Function>(GV);
1341
1342 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001343 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001344 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001345 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1346 llvm::AttributeSet::get(CGM.getLLVMContext(),
1347 llvm::AttributeSet::FunctionIndex,
1348 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001349 }
1350 }
1351}
1352
John McCallbeec5a02010-03-06 00:35:14 +00001353bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1354 CodeGen::CodeGenFunction &CGF,
1355 llvm::Value *Address) const {
1356 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001357
Chris Lattnerece04092012-02-07 00:39:47 +00001358 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001359
John McCallbeec5a02010-03-06 00:35:14 +00001360 // 0-7 are the eight integer registers; the order is different
1361 // on Darwin (for EH), but the range is the same.
1362 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001363 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001364
John McCallc8e01702013-04-16 22:48:15 +00001365 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001366 // 12-16 are st(0..4). Not sure why we stop at 4.
1367 // These have size 16, which is sizeof(long double) on
1368 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001369 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001370 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001371
John McCallbeec5a02010-03-06 00:35:14 +00001372 } else {
1373 // 9 is %eflags, which doesn't get a size on Darwin for some
1374 // reason.
David Blaikiefb901c7a2015-04-04 15:12:29 +00001375 Builder.CreateStore(
1376 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9));
John McCallbeec5a02010-03-06 00:35:14 +00001377
1378 // 11-16 are st(0..5). Not sure why we stop at 5.
1379 // These have size 12, which is sizeof(long double) on
1380 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001381 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001382 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1383 }
John McCallbeec5a02010-03-06 00:35:14 +00001384
1385 return false;
1386}
1387
Chris Lattner0cf24192010-06-28 20:05:43 +00001388//===----------------------------------------------------------------------===//
1389// X86-64 ABI Implementation
1390//===----------------------------------------------------------------------===//
1391
1392
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001393namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001394/// The AVX ABI level for X86 targets.
1395enum class X86AVXABILevel {
1396 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001397 AVX,
1398 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001399};
1400
1401/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1402static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1403 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001404 case X86AVXABILevel::AVX512:
1405 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001406 case X86AVXABILevel::AVX:
1407 return 256;
1408 case X86AVXABILevel::None:
1409 return 128;
1410 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001411 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001412}
1413
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001414/// X86_64ABIInfo - The X86_64 ABI information.
1415class X86_64ABIInfo : public ABIInfo {
1416 enum Class {
1417 Integer = 0,
1418 SSE,
1419 SSEUp,
1420 X87,
1421 X87Up,
1422 ComplexX87,
1423 NoClass,
1424 Memory
1425 };
1426
1427 /// merge - Implement the X86_64 ABI merging algorithm.
1428 ///
1429 /// Merge an accumulating classification \arg Accum with a field
1430 /// classification \arg Field.
1431 ///
1432 /// \param Accum - The accumulating classification. This should
1433 /// always be either NoClass or the result of a previous merge
1434 /// call. In addition, this should never be Memory (the caller
1435 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001436 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001437
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001438 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1439 ///
1440 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1441 /// final MEMORY or SSE classes when necessary.
1442 ///
1443 /// \param AggregateSize - The size of the current aggregate in
1444 /// the classification process.
1445 ///
1446 /// \param Lo - The classification for the parts of the type
1447 /// residing in the low word of the containing object.
1448 ///
1449 /// \param Hi - The classification for the parts of the type
1450 /// residing in the higher words of the containing object.
1451 ///
1452 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1453
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001454 /// classify - Determine the x86_64 register classes in which the
1455 /// given type T should be passed.
1456 ///
1457 /// \param Lo - The classification for the parts of the type
1458 /// residing in the low word of the containing object.
1459 ///
1460 /// \param Hi - The classification for the parts of the type
1461 /// residing in the high word of the containing object.
1462 ///
1463 /// \param OffsetBase - The bit offset of this type in the
1464 /// containing object. Some parameters are classified different
1465 /// depending on whether they straddle an eightbyte boundary.
1466 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001467 /// \param isNamedArg - Whether the argument in question is a "named"
1468 /// argument, as used in AMD64-ABI 3.5.7.
1469 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001470 /// If a word is unused its result will be NoClass; if a type should
1471 /// be passed in Memory then at least the classification of \arg Lo
1472 /// will be Memory.
1473 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001474 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001475 ///
1476 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1477 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001478 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1479 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001481 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001482 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1483 unsigned IROffset, QualType SourceTy,
1484 unsigned SourceOffset) const;
1485 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1486 unsigned IROffset, QualType SourceTy,
1487 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001488
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001489 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001490 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001491 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001492
1493 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001494 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001495 ///
1496 /// \param freeIntRegs - The number of free integer registers remaining
1497 /// available.
1498 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001499
Chris Lattner458b2aa2010-07-29 02:16:43 +00001500 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001501
Bill Wendling5cd41c42010-10-18 03:41:31 +00001502 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001503 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001504 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001505 unsigned &neededSSE,
1506 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001507
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001508 bool IsIllegalVectorType(QualType Ty) const;
1509
John McCalle0fda732011-04-21 01:20:55 +00001510 /// The 0.98 ABI revision clarified a lot of ambiguities,
1511 /// unfortunately in ways that were not always consistent with
1512 /// certain previous compilers. In particular, platforms which
1513 /// required strict binary compatibility with older versions of GCC
1514 /// may need to exempt themselves.
1515 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001516 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001517 }
1518
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001519 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001520 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1521 // 64-bit hardware.
1522 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001523
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001524public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001525 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1526 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001527 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001528 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001529
John McCalla729c622012-02-17 03:33:10 +00001530 bool isPassedUsingAVXType(QualType type) const {
1531 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001532 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001533 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1534 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001535 if (info.isDirect()) {
1536 llvm::Type *ty = info.getCoerceToType();
1537 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1538 return (vectorTy->getBitWidth() > 128);
1539 }
1540 return false;
1541 }
1542
Craig Topper4f12f102014-03-12 06:41:41 +00001543 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001544
Craig Topper4f12f102014-03-12 06:41:41 +00001545 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1546 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001547
1548 bool has64BitPointers() const {
1549 return Has64BitPointers;
1550 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001551};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001552
Chris Lattner04dc9572010-08-31 16:44:54 +00001553/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001554class WinX86_64ABIInfo : public ABIInfo {
1555
Reid Kleckner80944df2014-10-31 22:00:51 +00001556 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1557 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001558
Chris Lattner04dc9572010-08-31 16:44:54 +00001559public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001560 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1561
Craig Topper4f12f102014-03-12 06:41:41 +00001562 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001563
Craig Topper4f12f102014-03-12 06:41:41 +00001564 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1565 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001566
1567 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1568 // FIXME: Assumes vectorcall is in use.
1569 return isX86VectorTypeForVectorCall(getContext(), Ty);
1570 }
1571
1572 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1573 uint64_t NumMembers) const override {
1574 // FIXME: Assumes vectorcall is in use.
1575 return isX86VectorCallAggregateSmallEnough(NumMembers);
1576 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001577};
1578
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001579class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1580public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001581 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001582 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001583
John McCalla729c622012-02-17 03:33:10 +00001584 const X86_64ABIInfo &getABIInfo() const {
1585 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1586 }
1587
Craig Topper4f12f102014-03-12 06:41:41 +00001588 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001589 return 7;
1590 }
1591
1592 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001593 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001594 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001595
John McCall943fae92010-05-27 06:19:26 +00001596 // 0-15 are the 16 integer registers.
1597 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001598 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001599 return false;
1600 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001601
Jay Foad7c57be32011-07-11 09:56:20 +00001602 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001603 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001604 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001605 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1606 }
1607
John McCalla729c622012-02-17 03:33:10 +00001608 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001609 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001610 // The default CC on x86-64 sets %al to the number of SSA
1611 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001612 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001613 // that when AVX types are involved: the ABI explicitly states it is
1614 // undefined, and it doesn't work in practice because of how the ABI
1615 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001616 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001617 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001618 for (CallArgList::const_iterator
1619 it = args.begin(), ie = args.end(); it != ie; ++it) {
1620 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1621 HasAVXType = true;
1622 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001623 }
1624 }
John McCalla729c622012-02-17 03:33:10 +00001625
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001626 if (!HasAVXType)
1627 return true;
1628 }
John McCallcbc038a2011-09-21 08:08:30 +00001629
John McCalla729c622012-02-17 03:33:10 +00001630 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001631 }
1632
Craig Topper4f12f102014-03-12 06:41:41 +00001633 llvm::Constant *
1634 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001635 unsigned Sig;
1636 if (getABIInfo().has64BitPointers())
1637 Sig = (0xeb << 0) | // jmp rel8
1638 (0x0a << 8) | // .+0x0c
1639 ('F' << 16) |
1640 ('T' << 24);
1641 else
1642 Sig = (0xeb << 0) | // jmp rel8
1643 (0x06 << 8) | // .+0x08
1644 ('F' << 16) |
1645 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001646 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1647 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001648};
1649
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001650class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1651public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001652 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1653 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001654
1655 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001656 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001657 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001658 // If the argument contains a space, enclose it in quotes.
1659 if (Lib.find(" ") != StringRef::npos)
1660 Opt += "\"" + Lib.str() + "\"";
1661 else
1662 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001663 }
1664};
1665
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001666static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001667 // If the argument does not end in .lib, automatically add the suffix.
1668 // If the argument contains a space, enclose it in quotes.
1669 // This matches the behavior of MSVC.
1670 bool Quote = (Lib.find(" ") != StringRef::npos);
1671 std::string ArgStr = Quote ? "\"" : "";
1672 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001673 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001674 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001675 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001676 return ArgStr;
1677}
1678
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001679class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1680public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001681 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1682 bool d, bool p, bool w, unsigned RegParms)
1683 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001684
Eric Christopher162c91c2015-06-05 22:03:00 +00001685 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001686 CodeGen::CodeGenModule &CGM) const override;
1687
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001688 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001689 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001690 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001691 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001692 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001693
1694 void getDetectMismatchOption(llvm::StringRef Name,
1695 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001696 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001697 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001698 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001699};
1700
Hans Wennborg77dc2362015-01-20 19:45:50 +00001701static void addStackProbeSizeTargetAttribute(const Decl *D,
1702 llvm::GlobalValue *GV,
1703 CodeGen::CodeGenModule &CGM) {
1704 if (isa<FunctionDecl>(D)) {
1705 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1706 llvm::Function *Fn = cast<llvm::Function>(GV);
1707
Eric Christopher7565e0d2015-05-29 23:09:49 +00001708 Fn->addFnAttr("stack-probe-size",
1709 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001710 }
1711 }
1712}
1713
Eric Christopher162c91c2015-06-05 22:03:00 +00001714void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001715 llvm::GlobalValue *GV,
1716 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001717 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001718
1719 addStackProbeSizeTargetAttribute(D, GV, CGM);
1720}
1721
Chris Lattner04dc9572010-08-31 16:44:54 +00001722class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1723public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001724 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1725 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001726 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001727
Eric Christopher162c91c2015-06-05 22:03:00 +00001728 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001729 CodeGen::CodeGenModule &CGM) const override;
1730
Craig Topper4f12f102014-03-12 06:41:41 +00001731 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001732 return 7;
1733 }
1734
1735 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001736 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001737 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001738
Chris Lattner04dc9572010-08-31 16:44:54 +00001739 // 0-15 are the 16 integer registers.
1740 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001741 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001742 return false;
1743 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001744
1745 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001746 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001747 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001748 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001749 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001750
1751 void getDetectMismatchOption(llvm::StringRef Name,
1752 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001753 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001754 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001755 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001756};
1757
Eric Christopher162c91c2015-06-05 22:03:00 +00001758void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001759 llvm::GlobalValue *GV,
1760 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001761 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001762
1763 addStackProbeSizeTargetAttribute(D, GV, CGM);
1764}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001765}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001766
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001767void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1768 Class &Hi) const {
1769 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1770 //
1771 // (a) If one of the classes is Memory, the whole argument is passed in
1772 // memory.
1773 //
1774 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1775 // memory.
1776 //
1777 // (c) If the size of the aggregate exceeds two eightbytes and the first
1778 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1779 // argument is passed in memory. NOTE: This is necessary to keep the
1780 // ABI working for processors that don't support the __m256 type.
1781 //
1782 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1783 //
1784 // Some of these are enforced by the merging logic. Others can arise
1785 // only with unions; for example:
1786 // union { _Complex double; unsigned; }
1787 //
1788 // Note that clauses (b) and (c) were added in 0.98.
1789 //
1790 if (Hi == Memory)
1791 Lo = Memory;
1792 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1793 Lo = Memory;
1794 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1795 Lo = Memory;
1796 if (Hi == SSEUp && Lo != SSE)
1797 Hi = SSE;
1798}
1799
Chris Lattnerd776fb12010-06-28 21:43:59 +00001800X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001801 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1802 // classified recursively so that always two fields are
1803 // considered. The resulting class is calculated according to
1804 // the classes of the fields in the eightbyte:
1805 //
1806 // (a) If both classes are equal, this is the resulting class.
1807 //
1808 // (b) If one of the classes is NO_CLASS, the resulting class is
1809 // the other class.
1810 //
1811 // (c) If one of the classes is MEMORY, the result is the MEMORY
1812 // class.
1813 //
1814 // (d) If one of the classes is INTEGER, the result is the
1815 // INTEGER.
1816 //
1817 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1818 // MEMORY is used as class.
1819 //
1820 // (f) Otherwise class SSE is used.
1821
1822 // Accum should never be memory (we should have returned) or
1823 // ComplexX87 (because this cannot be passed in a structure).
1824 assert((Accum != Memory && Accum != ComplexX87) &&
1825 "Invalid accumulated classification during merge.");
1826 if (Accum == Field || Field == NoClass)
1827 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001828 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001829 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001830 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001831 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001832 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001833 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001834 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1835 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001836 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001837 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001838}
1839
Chris Lattner5c740f12010-06-30 19:14:05 +00001840void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001841 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001842 // FIXME: This code can be simplified by introducing a simple value class for
1843 // Class pairs with appropriate constructor methods for the various
1844 // situations.
1845
1846 // FIXME: Some of the split computations are wrong; unaligned vectors
1847 // shouldn't be passed in registers for example, so there is no chance they
1848 // can straddle an eightbyte. Verify & simplify.
1849
1850 Lo = Hi = NoClass;
1851
1852 Class &Current = OffsetBase < 64 ? Lo : Hi;
1853 Current = Memory;
1854
John McCall9dd450b2009-09-21 23:43:11 +00001855 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001856 BuiltinType::Kind k = BT->getKind();
1857
1858 if (k == BuiltinType::Void) {
1859 Current = NoClass;
1860 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1861 Lo = Integer;
1862 Hi = Integer;
1863 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1864 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001865 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001866 Current = SSE;
1867 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001868 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1869 if (LDF == &llvm::APFloat::IEEEquad) {
1870 Lo = SSE;
1871 Hi = SSEUp;
1872 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
1873 Lo = X87;
1874 Hi = X87Up;
1875 } else if (LDF == &llvm::APFloat::IEEEdouble) {
1876 Current = SSE;
1877 } else
1878 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001879 }
1880 // FIXME: _Decimal32 and _Decimal64 are SSE.
1881 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001882 return;
1883 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001884
Chris Lattnerd776fb12010-06-28 21:43:59 +00001885 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001886 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001887 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
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 (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001892 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001893 return;
1894 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001895
Chris Lattnerd776fb12010-06-28 21:43:59 +00001896 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001897 if (Ty->isMemberFunctionPointerType()) {
1898 if (Has64BitPointers) {
1899 // If Has64BitPointers, this is an {i64, i64}, so classify both
1900 // Lo and Hi now.
1901 Lo = Hi = Integer;
1902 } else {
1903 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1904 // straddles an eightbyte boundary, Hi should be classified as well.
1905 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1906 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1907 if (EB_FuncPtr != EB_ThisAdj) {
1908 Lo = Hi = Integer;
1909 } else {
1910 Current = Integer;
1911 }
1912 }
1913 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001914 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001915 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001916 return;
1917 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001918
Chris Lattnerd776fb12010-06-28 21:43:59 +00001919 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001920 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00001921 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
1922 // gcc passes the following as integer:
1923 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
1924 // 2 bytes - <2 x char>, <1 x short>
1925 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001926 Current = Integer;
1927
1928 // If this type crosses an eightbyte boundary, it should be
1929 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00001930 uint64_t EB_Lo = (OffsetBase) / 64;
1931 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
1932 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001933 Hi = Lo;
1934 } else if (Size == 64) {
1935 // gcc passes <1 x double> in memory. :(
1936 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1937 return;
1938
1939 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001940 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001941 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1942 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1943 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001944 Current = Integer;
1945 else
1946 Current = SSE;
1947
1948 // If this type crosses an eightbyte boundary, it should be
1949 // split.
1950 if (OffsetBase && OffsetBase != 64)
1951 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001952 } else if (Size == 128 ||
1953 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001954 // Arguments of 256-bits are split into four eightbyte chunks. The
1955 // least significant one belongs to class SSE and all the others to class
1956 // SSEUP. The original Lo and Hi design considers that types can't be
1957 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1958 // This design isn't correct for 256-bits, but since there're no cases
1959 // where the upper parts would need to be inspected, avoid adding
1960 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001961 //
1962 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1963 // registers if they are "named", i.e. not part of the "..." of a
1964 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001965 //
1966 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
1967 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001968 Lo = SSE;
1969 Hi = SSEUp;
1970 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001971 return;
1972 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001973
Chris Lattnerd776fb12010-06-28 21:43:59 +00001974 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001975 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001976
Chris Lattner2b037972010-07-29 02:01:43 +00001977 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001978 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001979 if (Size <= 64)
1980 Current = Integer;
1981 else if (Size <= 128)
1982 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001983 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001984 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001985 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001986 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00001987 } else if (ET == getContext().LongDoubleTy) {
1988 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1989 if (LDF == &llvm::APFloat::IEEEquad)
1990 Current = Memory;
1991 else if (LDF == &llvm::APFloat::x87DoubleExtended)
1992 Current = ComplexX87;
1993 else if (LDF == &llvm::APFloat::IEEEdouble)
1994 Lo = Hi = SSE;
1995 else
1996 llvm_unreachable("unexpected long double representation!");
1997 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001998
1999 // If this complex type crosses an eightbyte boundary then it
2000 // should be split.
2001 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002002 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002003 if (Hi == NoClass && EB_Real != EB_Imag)
2004 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002005
Chris Lattnerd776fb12010-06-28 21:43:59 +00002006 return;
2007 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002008
Chris Lattner2b037972010-07-29 02:01:43 +00002009 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010 // Arrays are treated like structures.
2011
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
2019 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2020 // fields, it has class MEMORY.
2021 //
2022 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002023 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002024 return;
2025
2026 // Otherwise implement simplified merge. We could be smarter about
2027 // this, but it isn't worth it and would be harder to verify.
2028 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002029 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002030 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002031
2032 // The only case a 256-bit wide vector could be used is when the array
2033 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2034 // to work for sizes wider than 128, early check and fallback to memory.
2035 if (Size > 128 && EltSize != 256)
2036 return;
2037
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002038 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2039 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002040 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002041 Lo = merge(Lo, FieldLo);
2042 Hi = merge(Hi, FieldHi);
2043 if (Lo == Memory || Hi == Memory)
2044 break;
2045 }
2046
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002047 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002048 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002049 return;
2050 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002051
Chris Lattnerd776fb12010-06-28 21:43:59 +00002052 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002053 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002054
2055 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002056 // than four eightbytes, ..., it has class MEMORY.
2057 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002058 return;
2059
Anders Carlsson20759ad2009-09-16 15:53:40 +00002060 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2061 // copy constructor or a non-trivial destructor, it is passed by invisible
2062 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002063 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002064 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002065
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002066 const RecordDecl *RD = RT->getDecl();
2067
2068 // Assume variable sized types are passed in memory.
2069 if (RD->hasFlexibleArrayMember())
2070 return;
2071
Chris Lattner2b037972010-07-29 02:01:43 +00002072 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002073
2074 // Reset Lo class, this will be recomputed.
2075 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002076
2077 // If this is a C++ record, classify the bases first.
2078 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002079 for (const auto &I : CXXRD->bases()) {
2080 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002081 "Unexpected base class!");
2082 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002083 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002084
2085 // Classify this field.
2086 //
2087 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2088 // single eightbyte, each is classified separately. Each eightbyte gets
2089 // initialized to class NO_CLASS.
2090 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002091 uint64_t Offset =
2092 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002093 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002094 Lo = merge(Lo, FieldLo);
2095 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002096 if (Lo == Memory || Hi == Memory) {
2097 postMerge(Size, Lo, Hi);
2098 return;
2099 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002100 }
2101 }
2102
2103 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002104 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002105 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002106 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002107 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2108 bool BitField = i->isBitField();
2109
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002110 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2111 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002112 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002113 // The only case a 256-bit wide vector could be used is when the struct
2114 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2115 // to work for sizes wider than 128, early check and fallback to memory.
2116 //
2117 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2118 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002119 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002120 return;
2121 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002122 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002123 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002124 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002125 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002126 return;
2127 }
2128
2129 // Classify this field.
2130 //
2131 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2132 // exceeds a single eightbyte, each is classified
2133 // separately. Each eightbyte gets initialized to class
2134 // NO_CLASS.
2135 Class FieldLo, FieldHi;
2136
2137 // Bit-fields require special handling, they do not force the
2138 // structure to be passed in memory even if unaligned, and
2139 // therefore they can straddle an eightbyte.
2140 if (BitField) {
2141 // Ignore padding bit-fields.
2142 if (i->isUnnamedBitfield())
2143 continue;
2144
2145 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002146 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002147
2148 uint64_t EB_Lo = Offset / 64;
2149 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002150
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002151 if (EB_Lo) {
2152 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2153 FieldLo = NoClass;
2154 FieldHi = Integer;
2155 } else {
2156 FieldLo = Integer;
2157 FieldHi = EB_Hi ? Integer : NoClass;
2158 }
2159 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002160 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002161 Lo = merge(Lo, FieldLo);
2162 Hi = merge(Hi, FieldHi);
2163 if (Lo == Memory || Hi == Memory)
2164 break;
2165 }
2166
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002167 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002168 }
2169}
2170
Chris Lattner22a931e2010-06-29 06:01:59 +00002171ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002172 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2173 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002174 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002175 // Treat an enum type as its underlying type.
2176 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2177 Ty = EnumTy->getDecl()->getIntegerType();
2178
2179 return (Ty->isPromotableIntegerType() ?
2180 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2181 }
2182
2183 return ABIArgInfo::getIndirect(0);
2184}
2185
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002186bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2187 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2188 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002189 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002190 if (Size <= 64 || Size > LargestVector)
2191 return true;
2192 }
2193
2194 return false;
2195}
2196
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002197ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2198 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002199 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2200 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002201 //
2202 // This assumption is optimistic, as there could be free registers available
2203 // when we need to pass this argument in memory, and LLVM could try to pass
2204 // the argument in the free register. This does not seem to happen currently,
2205 // but this code would be much safer if we could mark the argument with
2206 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002207 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002208 // Treat an enum type as its underlying type.
2209 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2210 Ty = EnumTy->getDecl()->getIntegerType();
2211
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002212 return (Ty->isPromotableIntegerType() ?
2213 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002214 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002215
Mark Lacey3825e832013-10-06 01:33:34 +00002216 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002217 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002218
Chris Lattner44c2b902011-05-22 23:21:23 +00002219 // Compute the byval alignment. We specify the alignment of the byval in all
2220 // cases so that the mid-level optimizer knows the alignment of the byval.
2221 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002222
2223 // Attempt to avoid passing indirect results using byval when possible. This
2224 // is important for good codegen.
2225 //
2226 // We do this by coercing the value into a scalar type which the backend can
2227 // handle naturally (i.e., without using byval).
2228 //
2229 // For simplicity, we currently only do this when we have exhausted all of the
2230 // free integer registers. Doing this when there are free integer registers
2231 // would require more care, as we would have to ensure that the coerced value
2232 // did not claim the unused register. That would require either reording the
2233 // arguments to the function (so that any subsequent inreg values came first),
2234 // or only doing this optimization when there were no following arguments that
2235 // might be inreg.
2236 //
2237 // We currently expect it to be rare (particularly in well written code) for
2238 // arguments to be passed on the stack when there are still free integer
2239 // registers available (this would typically imply large structs being passed
2240 // by value), so this seems like a fair tradeoff for now.
2241 //
2242 // We can revisit this if the backend grows support for 'onstack' parameter
2243 // attributes. See PR12193.
2244 if (freeIntRegs == 0) {
2245 uint64_t Size = getContext().getTypeSize(Ty);
2246
2247 // If this type fits in an eightbyte, coerce it into the matching integral
2248 // type, which will end up on the stack (with alignment 8).
2249 if (Align == 8 && Size <= 64)
2250 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2251 Size));
2252 }
2253
Chris Lattner44c2b902011-05-22 23:21:23 +00002254 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002255}
2256
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002257/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2258/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002259llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002260 // Wrapper structs/arrays that only contain vectors are passed just like
2261 // vectors; strip them off if present.
2262 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2263 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002264
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002265 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002266 if (isa<llvm::VectorType>(IRType) ||
2267 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002268 return IRType;
2269
2270 // We couldn't find the preferred IR vector type for 'Ty'.
2271 uint64_t Size = getContext().getTypeSize(Ty);
2272 assert((Size == 128 || Size == 256) && "Invalid type found!");
2273
2274 // Return a LLVM IR vector type based on the size of 'Ty'.
2275 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2276 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002277}
2278
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002279/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2280/// is known to either be off the end of the specified type or being in
2281/// alignment padding. The user type specified is known to be at most 128 bits
2282/// in size, and have passed through X86_64ABIInfo::classify with a successful
2283/// classification that put one of the two halves in the INTEGER class.
2284///
2285/// It is conservatively correct to return false.
2286static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2287 unsigned EndBit, ASTContext &Context) {
2288 // If the bytes being queried are off the end of the type, there is no user
2289 // data hiding here. This handles analysis of builtins, vectors and other
2290 // types that don't contain interesting padding.
2291 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2292 if (TySize <= StartBit)
2293 return true;
2294
Chris Lattner98076a22010-07-29 07:43:55 +00002295 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2296 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2297 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2298
2299 // Check each element to see if the element overlaps with the queried range.
2300 for (unsigned i = 0; i != NumElts; ++i) {
2301 // If the element is after the span we care about, then we're done..
2302 unsigned EltOffset = i*EltSize;
2303 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002304
Chris Lattner98076a22010-07-29 07:43:55 +00002305 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2306 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2307 EndBit-EltOffset, Context))
2308 return false;
2309 }
2310 // If it overlaps no elements, then it is safe to process as padding.
2311 return true;
2312 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002313
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002314 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2315 const RecordDecl *RD = RT->getDecl();
2316 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002317
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002318 // If this is a C++ record, check the bases first.
2319 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002320 for (const auto &I : CXXRD->bases()) {
2321 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002322 "Unexpected base class!");
2323 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002324 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002325
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002326 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002327 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002328 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002330 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002331 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002332 EndBit-BaseOffset, Context))
2333 return false;
2334 }
2335 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002336
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002337 // Verify that no field has data that overlaps the region of interest. Yes
2338 // this could be sped up a lot by being smarter about queried fields,
2339 // however we're only looking at structs up to 16 bytes, so we don't care
2340 // much.
2341 unsigned idx = 0;
2342 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2343 i != e; ++i, ++idx) {
2344 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002345
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002346 // If we found a field after the region we care about, then we're done.
2347 if (FieldOffset >= EndBit) break;
2348
2349 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2350 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2351 Context))
2352 return false;
2353 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002354
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002355 // If nothing in this record overlapped the area of interest, then we're
2356 // clean.
2357 return true;
2358 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002359
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002360 return false;
2361}
2362
Chris Lattnere556a712010-07-29 18:39:32 +00002363/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2364/// float member at the specified offset. For example, {int,{float}} has a
2365/// float at offset 4. It is conservatively correct for this routine to return
2366/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002367static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002368 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002369 // Base case if we find a float.
2370 if (IROffset == 0 && IRType->isFloatTy())
2371 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002372
Chris Lattnere556a712010-07-29 18:39:32 +00002373 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002374 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002375 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2376 unsigned Elt = SL->getElementContainingOffset(IROffset);
2377 IROffset -= SL->getElementOffset(Elt);
2378 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2379 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002380
Chris Lattnere556a712010-07-29 18:39:32 +00002381 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002382 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2383 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002384 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2385 IROffset -= IROffset/EltSize*EltSize;
2386 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2387 }
2388
2389 return false;
2390}
2391
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002392
2393/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2394/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002395llvm::Type *X86_64ABIInfo::
2396GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002397 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002398 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002399 // pass as float if the last 4 bytes is just padding. This happens for
2400 // structs that contain 3 floats.
2401 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2402 SourceOffset*8+64, getContext()))
2403 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002404
Chris Lattnere556a712010-07-29 18:39:32 +00002405 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2406 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2407 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002408 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2409 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002410 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002411
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002412 return llvm::Type::getDoubleTy(getVMContext());
2413}
2414
2415
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002416/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2417/// an 8-byte GPR. This means that we either have a scalar or we are talking
2418/// about the high or low part of an up-to-16-byte struct. This routine picks
2419/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002420/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2421/// etc).
2422///
2423/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2424/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2425/// the 8-byte value references. PrefType may be null.
2426///
Alp Toker9907f082014-07-09 14:06:35 +00002427/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002428/// an offset into this that we're processing (which is always either 0 or 8).
2429///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002430llvm::Type *X86_64ABIInfo::
2431GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002432 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002433 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2434 // returning an 8-byte unit starting with it. See if we can safely use it.
2435 if (IROffset == 0) {
2436 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002437 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2438 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002439 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002440
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002441 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2442 // goodness in the source type is just tail padding. This is allowed to
2443 // kick in for struct {double,int} on the int, but not on
2444 // struct{double,int,int} because we wouldn't return the second int. We
2445 // have to do this analysis on the source type because we can't depend on
2446 // unions being lowered a specific way etc.
2447 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002448 IRType->isIntegerTy(32) ||
2449 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2450 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2451 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002452
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002453 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2454 SourceOffset*8+64, getContext()))
2455 return IRType;
2456 }
2457 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002458
Chris Lattner2192fe52011-07-18 04:24:23 +00002459 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002460 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002461 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002462 if (IROffset < SL->getSizeInBytes()) {
2463 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2464 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002465
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002466 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2467 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002468 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002469 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002470
Chris Lattner2192fe52011-07-18 04:24:23 +00002471 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002472 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002473 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002474 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002475 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2476 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002477 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002478
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002479 // Okay, we don't have any better idea of what to pass, so we pass this in an
2480 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002481 unsigned TySizeInBytes =
2482 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002483
Chris Lattner3f763422010-07-29 17:34:39 +00002484 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002485
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002486 // It is always safe to classify this as an integer type up to i64 that
2487 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002488 return llvm::IntegerType::get(getVMContext(),
2489 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002490}
2491
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002492
2493/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2494/// be used as elements of a two register pair to pass or return, return a
2495/// first class aggregate to represent them. For example, if the low part of
2496/// a by-value argument should be passed as i32* and the high part as float,
2497/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002498static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002499GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002500 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002501 // In order to correctly satisfy the ABI, we need to the high part to start
2502 // at offset 8. If the high and low parts we inferred are both 4-byte types
2503 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2504 // the second element at offset 8. Check for this:
2505 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2506 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002507 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002508 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002509
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002510 // To handle this, we have to increase the size of the low part so that the
2511 // second element will start at an 8 byte offset. We can't increase the size
2512 // of the second element because it might make us access off the end of the
2513 // struct.
2514 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002515 // There are usually two sorts of types the ABI generation code can produce
2516 // for the low part of a pair that aren't 8 bytes in size: float or
2517 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2518 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002519 // Promote these to a larger type.
2520 if (Lo->isFloatTy())
2521 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2522 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002523 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2524 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002525 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2526 }
2527 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002528
Reid Kleckneree7cf842014-12-01 22:02:27 +00002529 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002530
2531
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002532 // Verify that the second element is at an 8-byte offset.
2533 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2534 "Invalid x86-64 argument pair!");
2535 return Result;
2536}
2537
Chris Lattner31faff52010-07-28 23:06:14 +00002538ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002539classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002540 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2541 // classification algorithm.
2542 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002543 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002544
2545 // Check some invariants.
2546 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002547 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2548
Craig Topper8a13c412014-05-21 05:09:00 +00002549 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002550 switch (Lo) {
2551 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002552 if (Hi == NoClass)
2553 return ABIArgInfo::getIgnore();
2554 // If the low part is just padding, it takes no register, leave ResType
2555 // null.
2556 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2557 "Unknown missing lo part");
2558 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002559
2560 case SSEUp:
2561 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002562 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002563
2564 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2565 // hidden argument.
2566 case Memory:
2567 return getIndirectReturnResult(RetTy);
2568
2569 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2570 // available register of the sequence %rax, %rdx is used.
2571 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002572 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002573
Chris Lattner1f3a0632010-07-29 21:42:50 +00002574 // If we have a sign or zero extended integer, make sure to return Extend
2575 // so that the parameter gets the right LLVM IR attributes.
2576 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2577 // Treat an enum type as its underlying type.
2578 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2579 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002580
Chris Lattner1f3a0632010-07-29 21:42:50 +00002581 if (RetTy->isIntegralOrEnumerationType() &&
2582 RetTy->isPromotableIntegerType())
2583 return ABIArgInfo::getExtend();
2584 }
Chris Lattner31faff52010-07-28 23:06:14 +00002585 break;
2586
2587 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2588 // available SSE register of the sequence %xmm0, %xmm1 is used.
2589 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002590 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002591 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002592
2593 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2594 // returned on the X87 stack in %st0 as 80-bit x87 number.
2595 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002596 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002597 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002598
2599 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2600 // part of the value is returned in %st0 and the imaginary part in
2601 // %st1.
2602 case ComplexX87:
2603 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002604 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002605 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002606 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002607 break;
2608 }
2609
Craig Topper8a13c412014-05-21 05:09:00 +00002610 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002611 switch (Hi) {
2612 // Memory was handled previously and X87 should
2613 // never occur as a hi class.
2614 case Memory:
2615 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002616 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002617
2618 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002619 case NoClass:
2620 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002621
Chris Lattner52b3c132010-09-01 00:20:33 +00002622 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002623 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002624 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2625 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002626 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002627 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002628 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002629 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2630 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002631 break;
2632
2633 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002634 // is passed in the next available eightbyte chunk if the last used
2635 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002636 //
Chris Lattner57540c52011-04-15 05:22:18 +00002637 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002638 case SSEUp:
2639 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002640 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002641 break;
2642
2643 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2644 // returned together with the previous X87 value in %st0.
2645 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002646 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002647 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002648 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002649 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002650 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002651 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002652 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2653 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002654 }
Chris Lattner31faff52010-07-28 23:06:14 +00002655 break;
2656 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002657
Chris Lattner52b3c132010-09-01 00:20:33 +00002658 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002659 // known to pass in the high eightbyte of the result. We do this by forming a
2660 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002661 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002662 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002663
Chris Lattner1f3a0632010-07-29 21:42:50 +00002664 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002665}
2666
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002667ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002668 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2669 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002670 const
2671{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002672 Ty = useFirstFieldIfTransparentUnion(Ty);
2673
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002675 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002676
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002677 // Check some invariants.
2678 // FIXME: Enforce these by construction.
2679 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2681
2682 neededInt = 0;
2683 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002684 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 switch (Lo) {
2686 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002687 if (Hi == NoClass)
2688 return ABIArgInfo::getIgnore();
2689 // If the low part is just padding, it takes no register, leave ResType
2690 // null.
2691 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2692 "Unknown missing lo part");
2693 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002694
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002695 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2696 // on the stack.
2697 case Memory:
2698
2699 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2700 // COMPLEX_X87, it is passed in memory.
2701 case X87:
2702 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002703 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002704 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002705 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706
2707 case SSEUp:
2708 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002709 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002710
2711 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2712 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2713 // and %r9 is used.
2714 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002715 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002716
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002717 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002718 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002719
2720 // If we have a sign or zero extended integer, make sure to return Extend
2721 // so that the parameter gets the right LLVM IR attributes.
2722 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2723 // Treat an enum type as its underlying type.
2724 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2725 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002726
Chris Lattner1f3a0632010-07-29 21:42:50 +00002727 if (Ty->isIntegralOrEnumerationType() &&
2728 Ty->isPromotableIntegerType())
2729 return ABIArgInfo::getExtend();
2730 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002731
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002732 break;
2733
2734 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2735 // available SSE register is used, the registers are taken in the
2736 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002737 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002738 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002739 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002740 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002741 break;
2742 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002743 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744
Craig Topper8a13c412014-05-21 05:09:00 +00002745 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002746 switch (Hi) {
2747 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002748 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002749 // which is passed in memory.
2750 case Memory:
2751 case X87:
2752 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002753 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002754
2755 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002756
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002757 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002758 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002759 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002760 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002761
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002762 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2763 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002764 break;
2765
2766 // X87Up generally doesn't occur here (long double is passed in
2767 // memory), except in situations involving unions.
2768 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002769 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002770 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002771
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002772 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2773 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002774
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002775 ++neededSSE;
2776 break;
2777
2778 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2779 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002780 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002781 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002782 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002783 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002784 break;
2785 }
2786
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002787 // If a high part was specified, merge it together with the low part. It is
2788 // known to pass in the high eightbyte of the result. We do this by forming a
2789 // first class struct aggregate with the high and low part: {low, high}
2790 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002791 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002792
Chris Lattner1f3a0632010-07-29 21:42:50 +00002793 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794}
2795
Chris Lattner22326a12010-07-29 02:31:05 +00002796void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002797
Reid Kleckner40ca9132014-05-13 22:05:45 +00002798 if (!getCXXABI().classifyReturnType(FI))
2799 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002800
2801 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002802 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803
2804 // If the return value is indirect, then the hidden argument is consuming one
2805 // integer register.
2806 if (FI.getReturnInfo().isIndirect())
2807 --freeIntRegs;
2808
Peter Collingbournef7706832014-12-12 23:41:25 +00002809 // The chain argument effectively gives us another free register.
2810 if (FI.isChainCall())
2811 ++freeIntRegs;
2812
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002813 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2815 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002816 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002817 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002818 it != ie; ++it, ++ArgNo) {
2819 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002820
Bill Wendling9987c0e2010-10-18 23:51:38 +00002821 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002822 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002823 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002824
2825 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2826 // eightbyte of an argument, the whole argument is passed on the
2827 // stack. If registers have already been assigned for some
2828 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002829 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002830 freeIntRegs -= neededInt;
2831 freeSSERegs -= neededSSE;
2832 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002833 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002834 }
2835 }
2836}
2837
2838static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2839 QualType Ty,
2840 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002841 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2842 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002843 llvm::Value *overflow_arg_area =
2844 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2845
2846 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2847 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002848 // It isn't stated explicitly in the standard, but in practice we use
2849 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002850 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2851 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002852 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002853 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002854 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002855 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2856 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002857 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002858 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002859 overflow_arg_area =
2860 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2861 overflow_arg_area->getType(),
2862 "overflow_arg_area.align");
2863 }
2864
2865 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002866 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002867 llvm::Value *Res =
2868 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002869 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002870
2871 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2872 // l->overflow_arg_area + sizeof(type).
2873 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2874 // an 8 byte boundary.
2875
2876 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002877 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002878 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002879 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2880 "overflow_arg_area.next");
2881 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2882
2883 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2884 return Res;
2885}
2886
2887llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2888 CodeGenFunction &CGF) const {
2889 // Assume that va_list type is correct; should be pointer to LLVM type:
2890 // struct {
2891 // i32 gp_offset;
2892 // i32 fp_offset;
2893 // i8* overflow_arg_area;
2894 // i8* reg_save_area;
2895 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002896 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002897
Chris Lattner9723d6c2010-03-11 18:19:55 +00002898 Ty = CGF.getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00002899 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002900 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002901
2902 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2903 // in the registers. If not go to step 7.
2904 if (!neededInt && !neededSSE)
2905 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2906
2907 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2908 // general purpose registers needed to pass type and num_fp to hold
2909 // the number of floating point registers needed.
2910
2911 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2912 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2913 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2914 //
2915 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2916 // register save space).
2917
Craig Topper8a13c412014-05-21 05:09:00 +00002918 llvm::Value *InRegs = nullptr;
2919 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2920 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002921 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002922 gp_offset_p =
2923 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002924 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002925 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2926 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002927 }
2928
2929 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002930 fp_offset_p =
2931 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002932 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2933 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002934 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2935 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002936 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2937 }
2938
2939 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2940 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2941 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2942 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2943
2944 // Emit code to load the value if it was passed in registers.
2945
2946 CGF.EmitBlock(InRegBlock);
2947
2948 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2949 // an offset of l->gp_offset and/or l->fp_offset. This may require
2950 // copying to a temporary location in case the parameter is passed
2951 // in different register classes or requires an alignment greater
2952 // than 8 for general purpose registers and 16 for XMM registers.
2953 //
2954 // FIXME: This really results in shameful code when we end up needing to
2955 // collect arguments from different places; often what should result in a
2956 // simple assembling of a structure from scattered addresses has many more
2957 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002958 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002959 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2960 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002961 if (neededInt && neededSSE) {
2962 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002963 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002964 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002965 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2966 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002967 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002968 llvm::Type *TyLo = ST->getElementType(0);
2969 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002970 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002971 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002972 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2973 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002974 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2975 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002976 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2977 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002978 llvm::Value *V =
2979 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002980 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002981 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002982 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002983
Owen Anderson170229f2009-07-14 23:10:40 +00002984 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002985 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002986 } else if (neededInt) {
2987 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2988 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002989 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002990
2991 // Copy to a temporary if necessary to ensure the appropriate alignment.
2992 std::pair<CharUnits, CharUnits> SizeAlign =
2993 CGF.getContext().getTypeInfoInChars(Ty);
2994 uint64_t TySize = SizeAlign.first.getQuantity();
2995 unsigned TyAlign = SizeAlign.second.getQuantity();
2996 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002997 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2998 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2999 RegAddr = Tmp;
3000 }
Chris Lattner0cf24192010-06-28 20:05:43 +00003001 } else if (neededSSE == 1) {
3002 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
3003 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
3004 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003005 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003006 assert(neededSSE == 2 && "Invalid number of needed registers!");
3007 // SSE registers are spaced 16 bytes apart in the register save
3008 // area, we need to collect the two eightbytes together.
3009 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00003010 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00003011 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00003012 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00003013 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003014 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003015 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
3016 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00003017 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
3018 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00003019 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00003020 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
3021 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00003022 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00003023 RegAddr = CGF.Builder.CreateBitCast(Tmp,
3024 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003025 }
3026
3027 // AMD64-ABI 3.5.7p5: Step 5. Set:
3028 // l->gp_offset = l->gp_offset + num_gp * 8
3029 // l->fp_offset = l->fp_offset + num_fp * 16.
3030 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003031 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003032 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3033 gp_offset_p);
3034 }
3035 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003036 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003037 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3038 fp_offset_p);
3039 }
3040 CGF.EmitBranch(ContBlock);
3041
3042 // Emit code to load the value if it was passed in memory.
3043
3044 CGF.EmitBlock(InMemBlock);
3045 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
3046
3047 // Return the appropriate result.
3048
3049 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00003050 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003051 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003052 ResAddr->addIncoming(RegAddr, InRegBlock);
3053 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003054 return ResAddr;
3055}
3056
Reid Kleckner80944df2014-10-31 22:00:51 +00003057ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3058 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003059
3060 if (Ty->isVoidType())
3061 return ABIArgInfo::getIgnore();
3062
3063 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3064 Ty = EnumTy->getDecl()->getIntegerType();
3065
Reid Kleckner80944df2014-10-31 22:00:51 +00003066 TypeInfo Info = getContext().getTypeInfo(Ty);
3067 uint64_t Width = Info.Width;
3068 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003069
Reid Kleckner9005f412014-05-02 00:51:20 +00003070 const RecordType *RT = Ty->getAs<RecordType>();
3071 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003072 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003073 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003074 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3075 }
3076
3077 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003078 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3079
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003080 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003081 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003082 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003083 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003084 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003085
Reid Kleckner80944df2014-10-31 22:00:51 +00003086 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3087 // other targets.
3088 const Type *Base = nullptr;
3089 uint64_t NumElts = 0;
3090 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3091 if (FreeSSERegs >= NumElts) {
3092 FreeSSERegs -= NumElts;
3093 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3094 return ABIArgInfo::getDirect();
3095 return ABIArgInfo::getExpand();
3096 }
3097 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3098 }
3099
3100
Reid Klecknerec87fec2014-05-02 01:17:12 +00003101 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003102 // If the member pointer is represented by an LLVM int or ptr, pass it
3103 // directly.
3104 llvm::Type *LLTy = CGT.ConvertType(Ty);
3105 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3106 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003107 }
3108
Michael Kuperstein4f818702015-02-24 09:35:58 +00003109 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003110 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3111 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003112 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003113 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003114
Reid Kleckner9005f412014-05-02 00:51:20 +00003115 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003116 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003117 }
3118
Julien Lerouge10dcff82014-08-27 00:36:55 +00003119 // Bool type is always extended to the ABI, other builtin types are not
3120 // extended.
3121 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3122 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003123 return ABIArgInfo::getExtend();
3124
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003125 return ABIArgInfo::getDirect();
3126}
3127
3128void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003129 bool IsVectorCall =
3130 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003131
Reid Kleckner80944df2014-10-31 22:00:51 +00003132 // We can use up to 4 SSE return registers with vectorcall.
3133 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3134 if (!getCXXABI().classifyReturnType(FI))
3135 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3136
3137 // We can use up to 6 SSE register parameters with vectorcall.
3138 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003139 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003140 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003141}
3142
Chris Lattner04dc9572010-08-31 16:44:54 +00003143llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3144 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003145 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003146
Chris Lattner04dc9572010-08-31 16:44:54 +00003147 CGBuilderTy &Builder = CGF.Builder;
3148 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3149 "ap");
3150 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3151 llvm::Type *PTy =
3152 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3153 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3154
3155 uint64_t Offset =
3156 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3157 llvm::Value *NextAddr =
3158 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3159 "ap.next");
3160 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3161
3162 return AddrTyped;
3163}
Chris Lattner0cf24192010-06-28 20:05:43 +00003164
John McCallea8d8bb2010-03-11 00:10:12 +00003165// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003166namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003167/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3168class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003169public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003170 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3171
3172 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3173 CodeGenFunction &CGF) const override;
3174};
3175
3176class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3177public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003178 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3179 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003180
Craig Topper4f12f102014-03-12 06:41:41 +00003181 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003182 // This is recovered from gcc output.
3183 return 1; // r1 is the dedicated stack pointer
3184 }
3185
3186 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003187 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003188};
3189
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003190}
John McCallea8d8bb2010-03-11 00:10:12 +00003191
Roman Divacky8a12d842014-11-03 18:32:54 +00003192llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3193 QualType Ty,
3194 CodeGenFunction &CGF) const {
3195 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3196 // TODO: Implement this. For now ignore.
3197 (void)CTy;
3198 return nullptr;
3199 }
3200
3201 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003202 bool isInt =
3203 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003204 llvm::Type *CharPtr = CGF.Int8PtrTy;
3205 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3206
3207 CGBuilderTy &Builder = CGF.Builder;
3208 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3209 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003210 llvm::Value *FPRPtrAsInt =
3211 Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
Roman Divacky8a12d842014-11-03 18:32:54 +00003212 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003213 llvm::Value *OverflowAreaPtrAsInt =
3214 Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3215 llvm::Value *OverflowAreaPtr =
3216 Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3217 llvm::Value *RegsaveAreaPtrAsInt =
3218 Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3219 llvm::Value *RegsaveAreaPtr =
3220 Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003221 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3222 // Align GPR when TY is i64.
3223 if (isI64) {
3224 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3225 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3226 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3227 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3228 }
3229 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
Eric Christopher7565e0d2015-05-29 23:09:49 +00003230 llvm::Value *OverflowArea =
3231 Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3232 llvm::Value *OverflowAreaAsInt =
3233 Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3234 llvm::Value *RegsaveArea =
3235 Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3236 llvm::Value *RegsaveAreaAsInt =
3237 Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
Roman Divacky8a12d842014-11-03 18:32:54 +00003238
Eric Christopher7565e0d2015-05-29 23:09:49 +00003239 llvm::Value *CC =
3240 Builder.CreateICmpULT(isInt ? GPR : FPR, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003241
Eric Christopher7565e0d2015-05-29 23:09:49 +00003242 llvm::Value *RegConstant =
3243 Builder.CreateMul(isInt ? GPR : FPR, Builder.getInt8(isInt ? 4 : 8));
Roman Divacky8a12d842014-11-03 18:32:54 +00003244
Eric Christopher7565e0d2015-05-29 23:09:49 +00003245 llvm::Value *OurReg = Builder.CreateAdd(
3246 RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003247
3248 if (Ty->isFloatingType())
3249 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3250
3251 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3252 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3253 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3254
3255 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3256
3257 CGF.EmitBlock(UsingRegs);
3258
3259 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3260 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3261 // Increase the GPR/FPR indexes.
3262 if (isInt) {
3263 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3264 Builder.CreateStore(GPR, GPRPtr);
3265 } else {
3266 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3267 Builder.CreateStore(FPR, FPRPtr);
3268 }
3269 CGF.EmitBranch(Cont);
3270
3271 CGF.EmitBlock(UsingOverflow);
3272
3273 // Increase the overflow area.
3274 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003275 OverflowAreaAsInt =
3276 Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3277 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr),
3278 OverflowAreaPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003279 CGF.EmitBranch(Cont);
3280
3281 CGF.EmitBlock(Cont);
3282
3283 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3284 Result->addIncoming(Result1, UsingRegs);
3285 Result->addIncoming(Result2, UsingOverflow);
3286
3287 if (Ty->isAggregateType()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003288 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003289 return Builder.CreateLoad(AGGPtr, false, "aggr");
3290 }
3291
3292 return Result;
3293}
3294
John McCallea8d8bb2010-03-11 00:10:12 +00003295bool
3296PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3297 llvm::Value *Address) const {
3298 // This is calculated from the LLVM and GCC tables and verified
3299 // against gcc output. AFAIK all ABIs use the same encoding.
3300
3301 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003302
Chris Lattnerece04092012-02-07 00:39:47 +00003303 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003304 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3305 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3306 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3307
3308 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003309 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003310
3311 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003312 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003313
3314 // 64-76 are various 4-byte special-purpose registers:
3315 // 64: mq
3316 // 65: lr
3317 // 66: ctr
3318 // 67: ap
3319 // 68-75 cr0-7
3320 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003321 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003322
3323 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003324 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003325
3326 // 109: vrsave
3327 // 110: vscr
3328 // 111: spe_acc
3329 // 112: spefscr
3330 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003331 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003332
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003333 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003334}
3335
Roman Divackyd966e722012-05-09 18:22:46 +00003336// PowerPC-64
3337
3338namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003339/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3340class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003341public:
3342 enum ABIKind {
3343 ELFv1 = 0,
3344 ELFv2
3345 };
3346
3347private:
3348 static const unsigned GPRBits = 64;
3349 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003350 bool HasQPX;
3351
3352 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3353 // will be passed in a QPX register.
3354 bool IsQPXVectorTy(const Type *Ty) const {
3355 if (!HasQPX)
3356 return false;
3357
3358 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3359 unsigned NumElements = VT->getNumElements();
3360 if (NumElements == 1)
3361 return false;
3362
3363 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3364 if (getContext().getTypeSize(Ty) <= 256)
3365 return true;
3366 } else if (VT->getElementType()->
3367 isSpecificBuiltinType(BuiltinType::Float)) {
3368 if (getContext().getTypeSize(Ty) <= 128)
3369 return true;
3370 }
3371 }
3372
3373 return false;
3374 }
3375
3376 bool IsQPXVectorTy(QualType Ty) const {
3377 return IsQPXVectorTy(Ty.getTypePtr());
3378 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003379
3380public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003381 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3382 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003383
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003384 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003385 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003386
3387 ABIArgInfo classifyReturnType(QualType RetTy) const;
3388 ABIArgInfo classifyArgumentType(QualType Ty) const;
3389
Reid Klecknere9f6a712014-10-31 17:10:41 +00003390 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3391 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3392 uint64_t Members) const override;
3393
Bill Schmidt84d37792012-10-12 19:26:17 +00003394 // TODO: We can add more logic to computeInfo to improve performance.
3395 // Example: For aggregate arguments that fit in a register, we could
3396 // use getDirectInReg (as is done below for structs containing a single
3397 // floating-point value) to avoid pushing them to memory on function
3398 // entry. This would require changing the logic in PPCISelLowering
3399 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003400 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003401 if (!getCXXABI().classifyReturnType(FI))
3402 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003403 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003404 // We rely on the default argument classification for the most part.
3405 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003406 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003407 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003408 if (T) {
3409 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003410 if (IsQPXVectorTy(T) ||
3411 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003412 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003413 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003414 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003415 continue;
3416 }
3417 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003418 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003419 }
3420 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003421
Craig Topper4f12f102014-03-12 06:41:41 +00003422 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3423 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003424};
3425
3426class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003427
Bill Schmidt25cb3492012-10-03 19:18:57 +00003428public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003429 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003430 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003431 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003432
Craig Topper4f12f102014-03-12 06:41:41 +00003433 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003434 // This is recovered from gcc output.
3435 return 1; // r1 is the dedicated stack pointer
3436 }
3437
3438 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003439 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003440};
3441
Roman Divackyd966e722012-05-09 18:22:46 +00003442class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3443public:
3444 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3445
Craig Topper4f12f102014-03-12 06:41:41 +00003446 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003447 // This is recovered from gcc output.
3448 return 1; // r1 is the dedicated stack pointer
3449 }
3450
3451 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003452 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003453};
3454
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003455}
Roman Divackyd966e722012-05-09 18:22:46 +00003456
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003457// Return true if the ABI requires Ty to be passed sign- or zero-
3458// extended to 64 bits.
3459bool
3460PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3461 // Treat an enum type as its underlying type.
3462 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3463 Ty = EnumTy->getDecl()->getIntegerType();
3464
3465 // Promotable integer types are required to be promoted by the ABI.
3466 if (Ty->isPromotableIntegerType())
3467 return true;
3468
3469 // In addition to the usual promotable integer types, we also need to
3470 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3471 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3472 switch (BT->getKind()) {
3473 case BuiltinType::Int:
3474 case BuiltinType::UInt:
3475 return true;
3476 default:
3477 break;
3478 }
3479
3480 return false;
3481}
3482
Ulrich Weigand581badc2014-07-10 17:20:07 +00003483/// isAlignedParamType - Determine whether a type requires 16-byte
3484/// alignment in the parameter area.
3485bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003486PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3487 Align32 = false;
3488
Ulrich Weigand581badc2014-07-10 17:20:07 +00003489 // Complex types are passed just like their elements.
3490 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3491 Ty = CTy->getElementType();
3492
3493 // Only vector types of size 16 bytes need alignment (larger types are
3494 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003495 if (IsQPXVectorTy(Ty)) {
3496 if (getContext().getTypeSize(Ty) > 128)
3497 Align32 = true;
3498
3499 return true;
3500 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003501 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003502 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003503
3504 // For single-element float/vector structs, we consider the whole type
3505 // to have the same alignment requirements as its single element.
3506 const Type *AlignAsType = nullptr;
3507 const Type *EltType = isSingleElementStruct(Ty, getContext());
3508 if (EltType) {
3509 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003510 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003511 getContext().getTypeSize(EltType) == 128) ||
3512 (BT && BT->isFloatingPoint()))
3513 AlignAsType = EltType;
3514 }
3515
Ulrich Weigandb7122372014-07-21 00:48:09 +00003516 // Likewise for ELFv2 homogeneous aggregates.
3517 const Type *Base = nullptr;
3518 uint64_t Members = 0;
3519 if (!AlignAsType && Kind == ELFv2 &&
3520 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3521 AlignAsType = Base;
3522
Ulrich Weigand581badc2014-07-10 17:20:07 +00003523 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003524 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3525 if (getContext().getTypeSize(AlignAsType) > 128)
3526 Align32 = true;
3527
3528 return true;
3529 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003530 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003531 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003532
3533 // Otherwise, we only need alignment for any aggregate type that
3534 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003535 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3536 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3537 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003538 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003539 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003540
3541 return false;
3542}
3543
Ulrich Weigandb7122372014-07-21 00:48:09 +00003544/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3545/// aggregate. Base is set to the base element type, and Members is set
3546/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003547bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3548 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003549 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3550 uint64_t NElements = AT->getSize().getZExtValue();
3551 if (NElements == 0)
3552 return false;
3553 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3554 return false;
3555 Members *= NElements;
3556 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3557 const RecordDecl *RD = RT->getDecl();
3558 if (RD->hasFlexibleArrayMember())
3559 return false;
3560
3561 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003562
3563 // If this is a C++ record, check the bases first.
3564 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3565 for (const auto &I : CXXRD->bases()) {
3566 // Ignore empty records.
3567 if (isEmptyRecord(getContext(), I.getType(), true))
3568 continue;
3569
3570 uint64_t FldMembers;
3571 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3572 return false;
3573
3574 Members += FldMembers;
3575 }
3576 }
3577
Ulrich Weigandb7122372014-07-21 00:48:09 +00003578 for (const auto *FD : RD->fields()) {
3579 // Ignore (non-zero arrays of) empty records.
3580 QualType FT = FD->getType();
3581 while (const ConstantArrayType *AT =
3582 getContext().getAsConstantArrayType(FT)) {
3583 if (AT->getSize().getZExtValue() == 0)
3584 return false;
3585 FT = AT->getElementType();
3586 }
3587 if (isEmptyRecord(getContext(), FT, true))
3588 continue;
3589
3590 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3591 if (getContext().getLangOpts().CPlusPlus &&
3592 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3593 continue;
3594
3595 uint64_t FldMembers;
3596 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3597 return false;
3598
3599 Members = (RD->isUnion() ?
3600 std::max(Members, FldMembers) : Members + FldMembers);
3601 }
3602
3603 if (!Base)
3604 return false;
3605
3606 // Ensure there is no padding.
3607 if (getContext().getTypeSize(Base) * Members !=
3608 getContext().getTypeSize(Ty))
3609 return false;
3610 } else {
3611 Members = 1;
3612 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3613 Members = 2;
3614 Ty = CT->getElementType();
3615 }
3616
Reid Klecknere9f6a712014-10-31 17:10:41 +00003617 // Most ABIs only support float, double, and some vector type widths.
3618 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003619 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003620
3621 // The base type must be the same for all members. Types that
3622 // agree in both total size and mode (float vs. vector) are
3623 // treated as being equivalent here.
3624 const Type *TyPtr = Ty.getTypePtr();
3625 if (!Base)
3626 Base = TyPtr;
3627
3628 if (Base->isVectorType() != TyPtr->isVectorType() ||
3629 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3630 return false;
3631 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003632 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3633}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003634
Reid Klecknere9f6a712014-10-31 17:10:41 +00003635bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3636 // Homogeneous aggregates for ELFv2 must have base types of float,
3637 // double, long double, or 128-bit vectors.
3638 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3639 if (BT->getKind() == BuiltinType::Float ||
3640 BT->getKind() == BuiltinType::Double ||
3641 BT->getKind() == BuiltinType::LongDouble)
3642 return true;
3643 }
3644 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003645 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003646 return true;
3647 }
3648 return false;
3649}
3650
3651bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3652 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003653 // Vector types require one register, floating point types require one
3654 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003655 uint32_t NumRegs =
3656 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003657
3658 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003659 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003660}
3661
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003662ABIArgInfo
3663PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003664 Ty = useFirstFieldIfTransparentUnion(Ty);
3665
Bill Schmidt90b22c92012-11-27 02:46:43 +00003666 if (Ty->isAnyComplexType())
3667 return ABIArgInfo::getDirect();
3668
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003669 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3670 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003671 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003672 uint64_t Size = getContext().getTypeSize(Ty);
3673 if (Size > 128)
3674 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3675 else if (Size < 128) {
3676 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3677 return ABIArgInfo::getDirect(CoerceTy);
3678 }
3679 }
3680
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003681 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003682 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003683 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003684
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003685 bool Align32;
3686 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3687 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003688 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003689
3690 // ELFv2 homogeneous aggregates are passed as array types.
3691 const Type *Base = nullptr;
3692 uint64_t Members = 0;
3693 if (Kind == ELFv2 &&
3694 isHomogeneousAggregate(Ty, Base, Members)) {
3695 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3696 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3697 return ABIArgInfo::getDirect(CoerceTy);
3698 }
3699
Ulrich Weigand601957f2014-07-21 00:56:36 +00003700 // If an aggregate may end up fully in registers, we do not
3701 // use the ByVal method, but pass the aggregate as array.
3702 // This is usually beneficial since we avoid forcing the
3703 // back-end to store the argument to memory.
3704 uint64_t Bits = getContext().getTypeSize(Ty);
3705 if (Bits > 0 && Bits <= 8 * GPRBits) {
3706 llvm::Type *CoerceTy;
3707
3708 // Types up to 8 bytes are passed as integer type (which will be
3709 // properly aligned in the argument save area doubleword).
3710 if (Bits <= GPRBits)
3711 CoerceTy = llvm::IntegerType::get(getVMContext(),
3712 llvm::RoundUpToAlignment(Bits, 8));
3713 // Larger types are passed as arrays, with the base type selected
3714 // according to the required alignment in the save area.
3715 else {
3716 uint64_t RegBits = ABIAlign * 8;
3717 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3718 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3719 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3720 }
3721
3722 return ABIArgInfo::getDirect(CoerceTy);
3723 }
3724
Ulrich Weigandb7122372014-07-21 00:48:09 +00003725 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003726 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3727 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003728 }
3729
3730 return (isPromotableTypeForABI(Ty) ?
3731 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3732}
3733
3734ABIArgInfo
3735PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3736 if (RetTy->isVoidType())
3737 return ABIArgInfo::getIgnore();
3738
Bill Schmidta3d121c2012-12-17 04:20:17 +00003739 if (RetTy->isAnyComplexType())
3740 return ABIArgInfo::getDirect();
3741
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003742 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3743 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003744 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003745 uint64_t Size = getContext().getTypeSize(RetTy);
3746 if (Size > 128)
3747 return ABIArgInfo::getIndirect(0);
3748 else if (Size < 128) {
3749 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3750 return ABIArgInfo::getDirect(CoerceTy);
3751 }
3752 }
3753
Ulrich Weigandb7122372014-07-21 00:48:09 +00003754 if (isAggregateTypeForABI(RetTy)) {
3755 // ELFv2 homogeneous aggregates are returned as array types.
3756 const Type *Base = nullptr;
3757 uint64_t Members = 0;
3758 if (Kind == ELFv2 &&
3759 isHomogeneousAggregate(RetTy, Base, Members)) {
3760 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3761 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3762 return ABIArgInfo::getDirect(CoerceTy);
3763 }
3764
3765 // ELFv2 small aggregates are returned in up to two registers.
3766 uint64_t Bits = getContext().getTypeSize(RetTy);
3767 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3768 if (Bits == 0)
3769 return ABIArgInfo::getIgnore();
3770
3771 llvm::Type *CoerceTy;
3772 if (Bits > GPRBits) {
3773 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003774 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003775 } else
3776 CoerceTy = llvm::IntegerType::get(getVMContext(),
3777 llvm::RoundUpToAlignment(Bits, 8));
3778 return ABIArgInfo::getDirect(CoerceTy);
3779 }
3780
3781 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003782 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003783 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003784
3785 return (isPromotableTypeForABI(RetTy) ?
3786 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3787}
3788
Bill Schmidt25cb3492012-10-03 19:18:57 +00003789// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3790llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3791 QualType Ty,
3792 CodeGenFunction &CGF) const {
3793 llvm::Type *BP = CGF.Int8PtrTy;
3794 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3795
3796 CGBuilderTy &Builder = CGF.Builder;
3797 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3798 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3799
Ulrich Weigand581badc2014-07-10 17:20:07 +00003800 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003801 bool Align32;
3802 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003803 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003804 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3805 Builder.getInt64(Align32 ? 31 : 15));
3806 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3807 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003808 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3809 }
3810
Bill Schmidt924c4782013-01-14 17:45:36 +00003811 // Update the va_list pointer. The pointer should be bumped by the
3812 // size of the object. We can trust getTypeSize() except for a complex
3813 // type whose base type is smaller than a doubleword. For these, the
3814 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003815 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003816 QualType BaseTy;
3817 unsigned CplxBaseSize = 0;
3818
3819 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3820 BaseTy = CTy->getElementType();
3821 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3822 if (CplxBaseSize < 8)
3823 SizeInBytes = 16;
3824 }
3825
Bill Schmidt25cb3492012-10-03 19:18:57 +00003826 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3827 llvm::Value *NextAddr =
3828 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3829 "ap.next");
3830 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3831
Bill Schmidt924c4782013-01-14 17:45:36 +00003832 // If we have a complex type and the base type is smaller than 8 bytes,
3833 // the ABI calls for the real and imaginary parts to be right-adjusted
3834 // in separate doublewords. However, Clang expects us to produce a
3835 // pointer to a structure with the two parts packed tightly. So generate
3836 // loads of the real and imaginary parts relative to the va_list pointer,
3837 // and store them to a temporary structure.
3838 if (CplxBaseSize && CplxBaseSize < 8) {
3839 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3840 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003841 if (CGF.CGM.getDataLayout().isBigEndian()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003842 RealAddr =
3843 Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3844 ImagAddr =
3845 Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003846 } else {
3847 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3848 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003849 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3850 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3851 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3852 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3853 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003854 llvm::AllocaInst *Ptr =
3855 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3856 llvm::Value *RealPtr =
3857 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3858 llvm::Value *ImagPtr =
3859 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003860 Builder.CreateStore(Real, RealPtr, false);
3861 Builder.CreateStore(Imag, ImagPtr, false);
3862 return Ptr;
3863 }
3864
Bill Schmidt25cb3492012-10-03 19:18:57 +00003865 // If the argument is smaller than 8 bytes, it is right-adjusted in
3866 // its doubleword slot. Adjust the pointer to pick it up from the
3867 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003868 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003869 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3870 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3871 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3872 }
3873
3874 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3875 return Builder.CreateBitCast(Addr, PTy);
3876}
3877
3878static bool
3879PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3880 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003881 // This is calculated from the LLVM and GCC tables and verified
3882 // against gcc output. AFAIK all ABIs use the same encoding.
3883
3884 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3885
3886 llvm::IntegerType *i8 = CGF.Int8Ty;
3887 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3888 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3889 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3890
3891 // 0-31: r0-31, the 8-byte general-purpose registers
3892 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3893
3894 // 32-63: fp0-31, the 8-byte floating-point registers
3895 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3896
3897 // 64-76 are various 4-byte special-purpose registers:
3898 // 64: mq
3899 // 65: lr
3900 // 66: ctr
3901 // 67: ap
3902 // 68-75 cr0-7
3903 // 76: xer
3904 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3905
3906 // 77-108: v0-31, the 16-byte vector registers
3907 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3908
3909 // 109: vrsave
3910 // 110: vscr
3911 // 111: spe_acc
3912 // 112: spefscr
3913 // 113: sfp
3914 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3915
3916 return false;
3917}
John McCallea8d8bb2010-03-11 00:10:12 +00003918
Bill Schmidt25cb3492012-10-03 19:18:57 +00003919bool
3920PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3921 CodeGen::CodeGenFunction &CGF,
3922 llvm::Value *Address) const {
3923
3924 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3925}
3926
3927bool
3928PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3929 llvm::Value *Address) const {
3930
3931 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3932}
3933
Chris Lattner0cf24192010-06-28 20:05:43 +00003934//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003935// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003936//===----------------------------------------------------------------------===//
3937
3938namespace {
3939
Tim Northover573cbee2014-05-24 12:52:07 +00003940class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003941public:
3942 enum ABIKind {
3943 AAPCS = 0,
3944 DarwinPCS
3945 };
3946
3947private:
3948 ABIKind Kind;
3949
3950public:
Tim Northover573cbee2014-05-24 12:52:07 +00003951 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003952
3953private:
3954 ABIKind getABIKind() const { return Kind; }
3955 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3956
3957 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003958 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003959 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3960 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3961 uint64_t Members) const override;
3962
Tim Northovera2ee4332014-03-29 15:09:45 +00003963 bool isIllegalVectorType(QualType Ty) const;
3964
David Blaikie1cbb9712014-11-14 19:09:44 +00003965 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003966 if (!getCXXABI().classifyReturnType(FI))
3967 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003968
Tim Northoverb047bfa2014-11-27 21:02:49 +00003969 for (auto &it : FI.arguments())
3970 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003971 }
3972
3973 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3974 CodeGenFunction &CGF) const;
3975
3976 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3977 CodeGenFunction &CGF) const;
3978
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003979 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3980 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003981 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3982 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3983 }
3984};
3985
Tim Northover573cbee2014-05-24 12:52:07 +00003986class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003987public:
Tim Northover573cbee2014-05-24 12:52:07 +00003988 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3989 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003990
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003991 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003992 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3993 }
3994
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003995 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3996 return 31;
3997 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003998
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003999 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004000};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004001}
Tim Northovera2ee4332014-03-29 15:09:45 +00004002
Tim Northoverb047bfa2014-11-27 21:02:49 +00004003ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004004 Ty = useFirstFieldIfTransparentUnion(Ty);
4005
Tim Northovera2ee4332014-03-29 15:09:45 +00004006 // Handle illegal vector types here.
4007 if (isIllegalVectorType(Ty)) {
4008 uint64_t Size = getContext().getTypeSize(Ty);
4009 if (Size <= 32) {
4010 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004011 return ABIArgInfo::getDirect(ResType);
4012 }
4013 if (Size == 64) {
4014 llvm::Type *ResType =
4015 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004016 return ABIArgInfo::getDirect(ResType);
4017 }
4018 if (Size == 128) {
4019 llvm::Type *ResType =
4020 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004021 return ABIArgInfo::getDirect(ResType);
4022 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004023 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4024 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004025
4026 if (!isAggregateTypeForABI(Ty)) {
4027 // Treat an enum type as its underlying type.
4028 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4029 Ty = EnumTy->getDecl()->getIntegerType();
4030
Tim Northovera2ee4332014-03-29 15:09:45 +00004031 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4032 ? ABIArgInfo::getExtend()
4033 : ABIArgInfo::getDirect());
4034 }
4035
4036 // Structures with either a non-trivial destructor or a non-trivial
4037 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004038 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004039 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00004040 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004041 }
4042
4043 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4044 // elsewhere for GNU compatibility.
4045 if (isEmptyRecord(getContext(), Ty, true)) {
4046 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4047 return ABIArgInfo::getIgnore();
4048
Tim Northovera2ee4332014-03-29 15:09:45 +00004049 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4050 }
4051
4052 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004053 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004054 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004055 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004056 return ABIArgInfo::getDirect(
4057 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004058 }
4059
4060 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4061 uint64_t Size = getContext().getTypeSize(Ty);
4062 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004063 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004064 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004065
Tim Northovera2ee4332014-03-29 15:09:45 +00004066 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4067 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004068 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004069 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4070 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4071 }
4072 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4073 }
4074
Tim Northovera2ee4332014-03-29 15:09:45 +00004075 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4076}
4077
Tim Northover573cbee2014-05-24 12:52:07 +00004078ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004079 if (RetTy->isVoidType())
4080 return ABIArgInfo::getIgnore();
4081
4082 // Large vector types should be returned via memory.
4083 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4084 return ABIArgInfo::getIndirect(0);
4085
4086 if (!isAggregateTypeForABI(RetTy)) {
4087 // Treat an enum type as its underlying type.
4088 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4089 RetTy = EnumTy->getDecl()->getIntegerType();
4090
Tim Northover4dab6982014-04-18 13:46:08 +00004091 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4092 ? ABIArgInfo::getExtend()
4093 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004094 }
4095
Tim Northovera2ee4332014-03-29 15:09:45 +00004096 if (isEmptyRecord(getContext(), RetTy, true))
4097 return ABIArgInfo::getIgnore();
4098
Craig Topper8a13c412014-05-21 05:09:00 +00004099 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004100 uint64_t Members = 0;
4101 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004102 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4103 return ABIArgInfo::getDirect();
4104
4105 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4106 uint64_t Size = getContext().getTypeSize(RetTy);
4107 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004108 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004109 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004110
4111 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4112 // For aggregates with 16-byte alignment, we use i128.
4113 if (Alignment < 128 && Size == 128) {
4114 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4115 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4116 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004117 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4118 }
4119
4120 return ABIArgInfo::getIndirect(0);
4121}
4122
Tim Northover573cbee2014-05-24 12:52:07 +00004123/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4124bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004125 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4126 // Check whether VT is legal.
4127 unsigned NumElements = VT->getNumElements();
4128 uint64_t Size = getContext().getTypeSize(VT);
4129 // NumElements should be power of 2 between 1 and 16.
4130 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4131 return true;
4132 return Size != 64 && (Size != 128 || NumElements == 1);
4133 }
4134 return false;
4135}
4136
Reid Klecknere9f6a712014-10-31 17:10:41 +00004137bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4138 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4139 // point type or a short-vector type. This is the same as the 32-bit ABI,
4140 // but with the difference that any floating-point type is allowed,
4141 // including __fp16.
4142 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4143 if (BT->isFloatingPoint())
4144 return true;
4145 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4146 unsigned VecSize = getContext().getTypeSize(VT);
4147 if (VecSize == 64 || VecSize == 128)
4148 return true;
4149 }
4150 return false;
4151}
4152
4153bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4154 uint64_t Members) const {
4155 return Members <= 4;
4156}
4157
Tim Northoverb047bfa2014-11-27 21:02:49 +00004158llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4159 QualType Ty,
4160 CodeGenFunction &CGF) const {
4161 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004162 bool IsIndirect = AI.isIndirect();
4163
Tim Northoverb047bfa2014-11-27 21:02:49 +00004164 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4165 if (IsIndirect)
4166 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4167 else if (AI.getCoerceToType())
4168 BaseTy = AI.getCoerceToType();
4169
4170 unsigned NumRegs = 1;
4171 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4172 BaseTy = ArrTy->getElementType();
4173 NumRegs = ArrTy->getNumElements();
4174 }
4175 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4176
Tim Northovera2ee4332014-03-29 15:09:45 +00004177 // The AArch64 va_list type and handling is specified in the Procedure Call
4178 // Standard, section B.4:
4179 //
4180 // struct {
4181 // void *__stack;
4182 // void *__gr_top;
4183 // void *__vr_top;
4184 // int __gr_offs;
4185 // int __vr_offs;
4186 // };
4187
4188 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4189 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4190 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4191 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4192 auto &Ctx = CGF.getContext();
4193
Craig Topper8a13c412014-05-21 05:09:00 +00004194 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004195 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004196 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4197 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004198 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004199 reg_offs_p =
4200 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004201 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4202 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004203 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004204 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004205 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004206 reg_offs_p =
4207 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004208 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4209 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004210 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004211 }
4212
4213 //=======================================
4214 // Find out where argument was passed
4215 //=======================================
4216
4217 // If reg_offs >= 0 we're already using the stack for this type of
4218 // argument. We don't want to keep updating reg_offs (in case it overflows,
4219 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4220 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004221 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004222 UsingStack = CGF.Builder.CreateICmpSGE(
4223 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4224
4225 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4226
4227 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004228 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004229 CGF.EmitBlock(MaybeRegBlock);
4230
4231 // Integer arguments may need to correct register alignment (for example a
4232 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4233 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004234 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004235 int Align = Ctx.getTypeAlign(Ty) / 8;
4236
4237 reg_offs = CGF.Builder.CreateAdd(
4238 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4239 "align_regoffs");
4240 reg_offs = CGF.Builder.CreateAnd(
4241 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4242 "aligned_regoffs");
4243 }
4244
4245 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004246 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004247 NewOffset = CGF.Builder.CreateAdd(
4248 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4249 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4250
4251 // Now we're in a position to decide whether this argument really was in
4252 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004253 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004254 InRegs = CGF.Builder.CreateICmpSLE(
4255 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4256
4257 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4258
4259 //=======================================
4260 // Argument was in registers
4261 //=======================================
4262
4263 // Now we emit the code for if the argument was originally passed in
4264 // registers. First start the appropriate block:
4265 CGF.EmitBlock(InRegBlock);
4266
Craig Topper8a13c412014-05-21 05:09:00 +00004267 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004268 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4269 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004270 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4271 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004272 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004273 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4274
4275 if (IsIndirect) {
4276 // If it's been passed indirectly (actually a struct), whatever we find from
4277 // stored registers or on the stack will actually be a struct **.
4278 MemTy = llvm::PointerType::getUnqual(MemTy);
4279 }
4280
Craig Topper8a13c412014-05-21 05:09:00 +00004281 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004282 uint64_t NumMembers = 0;
4283 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004284 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004285 // Homogeneous aggregates passed in registers will have their elements split
4286 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4287 // qN+1, ...). We reload and store into a temporary local variable
4288 // contiguously.
4289 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4290 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4291 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004292 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004293 int Offset = 0;
4294
4295 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4296 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4297 for (unsigned i = 0; i < NumMembers; ++i) {
4298 llvm::Value *BaseOffset =
4299 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4300 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4301 LoadAddr = CGF.Builder.CreateBitCast(
4302 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004303 llvm::Value *StoreAddr =
4304 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004305
4306 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4307 CGF.Builder.CreateStore(Elem, StoreAddr);
4308 }
4309
4310 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4311 } else {
4312 // Otherwise the object is contiguous in memory
4313 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004314 if (CGF.CGM.getDataLayout().isBigEndian() &&
4315 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004316 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4317 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4318 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4319
4320 BaseAddr = CGF.Builder.CreateAdd(
4321 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4322
4323 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4324 }
4325
4326 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4327 }
4328
4329 CGF.EmitBranch(ContBlock);
4330
4331 //=======================================
4332 // Argument was on the stack
4333 //=======================================
4334 CGF.EmitBlock(OnStackBlock);
4335
Craig Topper8a13c412014-05-21 05:09:00 +00004336 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004337 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004338 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4339
4340 // Again, stack arguments may need realigmnent. In this case both integer and
4341 // floating-point ones might be affected.
4342 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4343 int Align = Ctx.getTypeAlign(Ty) / 8;
4344
4345 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4346
4347 OnStackAddr = CGF.Builder.CreateAdd(
4348 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4349 "align_stack");
4350 OnStackAddr = CGF.Builder.CreateAnd(
4351 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4352 "align_stack");
4353
4354 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4355 }
4356
4357 uint64_t StackSize;
4358 if (IsIndirect)
4359 StackSize = 8;
4360 else
4361 StackSize = Ctx.getTypeSize(Ty) / 8;
4362
4363 // All stack slots are 8 bytes
4364 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4365
4366 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4367 llvm::Value *NewStack =
4368 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4369
4370 // Write the new value of __stack for the next call to va_arg
4371 CGF.Builder.CreateStore(NewStack, stack_p);
4372
4373 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4374 Ctx.getTypeSize(Ty) < 64) {
4375 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4376 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4377
4378 OnStackAddr = CGF.Builder.CreateAdd(
4379 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4380
4381 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4382 }
4383
4384 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4385
4386 CGF.EmitBranch(ContBlock);
4387
4388 //=======================================
4389 // Tidy up
4390 //=======================================
4391 CGF.EmitBlock(ContBlock);
4392
4393 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4394 ResAddr->addIncoming(RegAddr, InRegBlock);
4395 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4396
4397 if (IsIndirect)
4398 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4399
4400 return ResAddr;
4401}
4402
Eric Christopher7565e0d2015-05-29 23:09:49 +00004403llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr,
4404 QualType Ty,
4405 CodeGenFunction &CGF) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004406 // We do not support va_arg for aggregates or illegal vector types.
4407 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4408 // other cases.
4409 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004410 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004411
4412 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4413 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4414
Craig Topper8a13c412014-05-21 05:09:00 +00004415 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004416 uint64_t Members = 0;
4417 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004418
4419 bool isIndirect = false;
4420 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4421 // be passed indirectly.
4422 if (Size > 16 && !isHA) {
4423 isIndirect = true;
4424 Size = 8;
4425 Align = 8;
4426 }
4427
4428 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4429 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4430
4431 CGBuilderTy &Builder = CGF.Builder;
4432 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4433 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4434
4435 if (isEmptyRecord(getContext(), Ty, true)) {
4436 // These are ignored for parameter passing purposes.
4437 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4438 return Builder.CreateBitCast(Addr, PTy);
4439 }
4440
4441 const uint64_t MinABIAlign = 8;
4442 if (Align > MinABIAlign) {
4443 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4444 Addr = Builder.CreateGEP(Addr, Offset);
4445 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4446 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4447 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4448 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4449 }
4450
4451 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4452 llvm::Value *NextAddr = Builder.CreateGEP(
4453 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4454 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4455
4456 if (isIndirect)
4457 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4458 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4459 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4460
4461 return AddrTyped;
4462}
4463
4464//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004465// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004466//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004467
4468namespace {
4469
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004470class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004471public:
4472 enum ABIKind {
4473 APCS = 0,
4474 AAPCS = 1,
4475 AAPCS_VFP
4476 };
4477
4478private:
4479 ABIKind Kind;
4480
4481public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004482 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004483 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004484 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004485
John McCall3480ef22011-08-30 01:42:09 +00004486 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004487 switch (getTarget().getTriple().getEnvironment()) {
4488 case llvm::Triple::Android:
4489 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004490 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004491 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004492 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004493 return true;
4494 default:
4495 return false;
4496 }
John McCall3480ef22011-08-30 01:42:09 +00004497 }
4498
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004499 bool isEABIHF() const {
4500 switch (getTarget().getTriple().getEnvironment()) {
4501 case llvm::Triple::EABIHF:
4502 case llvm::Triple::GNUEABIHF:
4503 return true;
4504 default:
4505 return false;
4506 }
4507 }
4508
Daniel Dunbar020daa92009-09-12 01:00:39 +00004509 ABIKind getABIKind() const { return Kind; }
4510
Tim Northovera484bc02013-10-01 14:34:25 +00004511private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004512 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004513 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004514 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004515
Reid Klecknere9f6a712014-10-31 17:10:41 +00004516 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4517 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4518 uint64_t Members) const override;
4519
Craig Topper4f12f102014-03-12 06:41:41 +00004520 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004521
Craig Topper4f12f102014-03-12 06:41:41 +00004522 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4523 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004524
4525 llvm::CallingConv::ID getLLVMDefaultCC() const;
4526 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004527 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004528};
4529
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004530class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4531public:
Chris Lattner2b037972010-07-29 02:01:43 +00004532 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4533 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004534
John McCall3480ef22011-08-30 01:42:09 +00004535 const ARMABIInfo &getABIInfo() const {
4536 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4537 }
4538
Craig Topper4f12f102014-03-12 06:41:41 +00004539 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004540 return 13;
4541 }
Roman Divackyc1617352011-05-18 19:36:54 +00004542
Craig Topper4f12f102014-03-12 06:41:41 +00004543 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004544 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4545 }
4546
Roman Divackyc1617352011-05-18 19:36:54 +00004547 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004548 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004549 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004550
4551 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004552 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004553 return false;
4554 }
John McCall3480ef22011-08-30 01:42:09 +00004555
Craig Topper4f12f102014-03-12 06:41:41 +00004556 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004557 if (getABIInfo().isEABI()) return 88;
4558 return TargetCodeGenInfo::getSizeOfUnwindException();
4559 }
Tim Northovera484bc02013-10-01 14:34:25 +00004560
Eric Christopher162c91c2015-06-05 22:03:00 +00004561 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004562 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004563 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4564 if (!FD)
4565 return;
4566
4567 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4568 if (!Attr)
4569 return;
4570
4571 const char *Kind;
4572 switch (Attr->getInterrupt()) {
4573 case ARMInterruptAttr::Generic: Kind = ""; break;
4574 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4575 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4576 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4577 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4578 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4579 }
4580
4581 llvm::Function *Fn = cast<llvm::Function>(GV);
4582
4583 Fn->addFnAttr("interrupt", Kind);
4584
4585 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4586 return;
4587
4588 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4589 // however this is not necessarily true on taking any interrupt. Instruct
4590 // the backend to perform a realignment as part of the function prologue.
4591 llvm::AttrBuilder B;
4592 B.addStackAlignmentAttr(8);
4593 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4594 llvm::AttributeSet::get(CGM.getLLVMContext(),
4595 llvm::AttributeSet::FunctionIndex,
4596 B));
4597 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004598};
4599
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004600class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4601 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4602 CodeGen::CodeGenModule &CGM) const;
4603
4604public:
4605 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4606 : ARMTargetCodeGenInfo(CGT, K) {}
4607
Eric Christopher162c91c2015-06-05 22:03:00 +00004608 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004609 CodeGen::CodeGenModule &CGM) const override;
4610};
4611
4612void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4613 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4614 if (!isa<FunctionDecl>(D))
4615 return;
4616 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4617 return;
4618
4619 llvm::Function *F = cast<llvm::Function>(GV);
4620 F->addFnAttr("stack-probe-size",
4621 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4622}
4623
Eric Christopher162c91c2015-06-05 22:03:00 +00004624void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004625 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004626 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004627 addStackProbeSizeTargetAttribute(D, GV, CGM);
4628}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004629}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004630
Chris Lattner22326a12010-07-29 02:31:05 +00004631void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004632 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004633 FI.getReturnInfo() =
4634 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004635
Tim Northoverbc784d12015-02-24 17:22:40 +00004636 for (auto &I : FI.arguments())
4637 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004638
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004639 // Always honor user-specified calling convention.
4640 if (FI.getCallingConvention() != llvm::CallingConv::C)
4641 return;
4642
John McCall882987f2013-02-28 19:01:20 +00004643 llvm::CallingConv::ID cc = getRuntimeCC();
4644 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004645 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004646}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004647
John McCall882987f2013-02-28 19:01:20 +00004648/// Return the default calling convention that LLVM will use.
4649llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4650 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004651 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004652 return llvm::CallingConv::ARM_AAPCS_VFP;
4653 else if (isEABI())
4654 return llvm::CallingConv::ARM_AAPCS;
4655 else
4656 return llvm::CallingConv::ARM_APCS;
4657}
4658
4659/// Return the calling convention that our ABI would like us to use
4660/// as the C calling convention.
4661llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004662 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004663 case APCS: return llvm::CallingConv::ARM_APCS;
4664 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4665 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004666 }
John McCall882987f2013-02-28 19:01:20 +00004667 llvm_unreachable("bad ABI kind");
4668}
4669
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004670void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004671 assert(getRuntimeCC() == llvm::CallingConv::C);
4672
4673 // Don't muddy up the IR with a ton of explicit annotations if
4674 // they'd just match what LLVM will infer from the triple.
4675 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4676 if (abiCC != getLLVMDefaultCC())
4677 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004678
4679 BuiltinCC = (getABIKind() == APCS ?
4680 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004681}
4682
Tim Northoverbc784d12015-02-24 17:22:40 +00004683ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4684 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004685 // 6.1.2.1 The following argument types are VFP CPRCs:
4686 // A single-precision floating-point type (including promoted
4687 // half-precision types); A double-precision floating-point type;
4688 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4689 // with a Base Type of a single- or double-precision floating-point type,
4690 // 64-bit containerized vectors or 128-bit containerized vectors with one
4691 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004692 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004693
Reid Klecknerb1be6832014-11-15 01:41:41 +00004694 Ty = useFirstFieldIfTransparentUnion(Ty);
4695
Manman Renfef9e312012-10-16 19:18:39 +00004696 // Handle illegal vector types here.
4697 if (isIllegalVectorType(Ty)) {
4698 uint64_t Size = getContext().getTypeSize(Ty);
4699 if (Size <= 32) {
4700 llvm::Type *ResType =
4701 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004702 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004703 }
4704 if (Size == 64) {
4705 llvm::Type *ResType = llvm::VectorType::get(
4706 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004707 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004708 }
4709 if (Size == 128) {
4710 llvm::Type *ResType = llvm::VectorType::get(
4711 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004712 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004713 }
4714 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4715 }
4716
John McCalla1dee5302010-08-22 10:59:02 +00004717 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004718 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004719 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004720 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004721 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004722
Tim Northover5a1558e2014-11-07 22:30:50 +00004723 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4724 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004725 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004726
Oliver Stannard405bded2014-02-11 09:25:50 +00004727 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004728 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004729 }
Tim Northover1060eae2013-06-21 22:49:34 +00004730
Daniel Dunbar09d33622009-09-14 21:54:03 +00004731 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004732 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004733 return ABIArgInfo::getIgnore();
4734
Tim Northover5a1558e2014-11-07 22:30:50 +00004735 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004736 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4737 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004738 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004739 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004740 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004741 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004742 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004743 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004744 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004745 }
4746
Manman Ren6c30e132012-08-13 21:23:55 +00004747 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004748 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4749 // most 8-byte. We realign the indirect argument if type alignment is bigger
4750 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004751 uint64_t ABIAlign = 4;
4752 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4753 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004754 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004755 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004756
Manman Ren8cd99812012-11-06 04:58:01 +00004757 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004758 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004759 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004760 }
4761
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004762 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004763 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004764 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004765 // FIXME: Try to match the types of the arguments more accurately where
4766 // we can.
4767 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004768 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4769 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004770 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004771 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4772 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004773 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004774
Tim Northover5a1558e2014-11-07 22:30:50 +00004775 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004776}
4777
Chris Lattner458b2aa2010-07-29 02:16:43 +00004778static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004779 llvm::LLVMContext &VMContext) {
4780 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4781 // is called integer-like if its size is less than or equal to one word, and
4782 // the offset of each of its addressable sub-fields is zero.
4783
4784 uint64_t Size = Context.getTypeSize(Ty);
4785
4786 // Check that the type fits in a word.
4787 if (Size > 32)
4788 return false;
4789
4790 // FIXME: Handle vector types!
4791 if (Ty->isVectorType())
4792 return false;
4793
Daniel Dunbard53bac72009-09-14 02:20:34 +00004794 // Float types are never treated as "integer like".
4795 if (Ty->isRealFloatingType())
4796 return false;
4797
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004798 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004799 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004800 return true;
4801
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004802 // Small complex integer types are "integer like".
4803 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4804 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004805
4806 // Single element and zero sized arrays should be allowed, by the definition
4807 // above, but they are not.
4808
4809 // Otherwise, it must be a record type.
4810 const RecordType *RT = Ty->getAs<RecordType>();
4811 if (!RT) return false;
4812
4813 // Ignore records with flexible arrays.
4814 const RecordDecl *RD = RT->getDecl();
4815 if (RD->hasFlexibleArrayMember())
4816 return false;
4817
4818 // Check that all sub-fields are at offset 0, and are themselves "integer
4819 // like".
4820 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4821
4822 bool HadField = false;
4823 unsigned idx = 0;
4824 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4825 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004826 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004827
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004828 // Bit-fields are not addressable, we only need to verify they are "integer
4829 // like". We still have to disallow a subsequent non-bitfield, for example:
4830 // struct { int : 0; int x }
4831 // is non-integer like according to gcc.
4832 if (FD->isBitField()) {
4833 if (!RD->isUnion())
4834 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004835
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004836 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4837 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004838
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004839 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004840 }
4841
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004842 // Check if this field is at offset 0.
4843 if (Layout.getFieldOffset(idx) != 0)
4844 return false;
4845
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004846 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4847 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004848
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004849 // Only allow at most one field in a structure. This doesn't match the
4850 // wording above, but follows gcc in situations with a field following an
4851 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004852 if (!RD->isUnion()) {
4853 if (HadField)
4854 return false;
4855
4856 HadField = true;
4857 }
4858 }
4859
4860 return true;
4861}
4862
Oliver Stannard405bded2014-02-11 09:25:50 +00004863ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4864 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004865 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004866
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004867 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004868 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004869
Daniel Dunbar19964db2010-09-23 01:54:32 +00004870 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004871 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004872 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004873 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004874
John McCalla1dee5302010-08-22 10:59:02 +00004875 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004876 // Treat an enum type as its underlying type.
4877 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4878 RetTy = EnumTy->getDecl()->getIntegerType();
4879
Tim Northover5a1558e2014-11-07 22:30:50 +00004880 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4881 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004882 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004883
4884 // Are we following APCS?
4885 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004886 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004887 return ABIArgInfo::getIgnore();
4888
Daniel Dunbareedf1512010-02-01 23:31:19 +00004889 // Complex types are all returned as packed integers.
4890 //
4891 // FIXME: Consider using 2 x vector types if the back end handles them
4892 // correctly.
4893 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004894 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4895 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004896
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004897 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004898 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004899 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004900 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004901 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004902 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004903 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004904 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4905 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004906 }
4907
4908 // Otherwise return in memory.
4909 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004910 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004911
4912 // Otherwise this is an AAPCS variant.
4913
Chris Lattner458b2aa2010-07-29 02:16:43 +00004914 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004915 return ABIArgInfo::getIgnore();
4916
Bob Wilson1d9269a2011-11-02 04:51:36 +00004917 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004918 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004919 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004920 uint64_t Members;
4921 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004922 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004923 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004924 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004925 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004926 }
4927
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004928 // Aggregates <= 4 bytes are returned in r0; other aggregates
4929 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004930 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004931 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004932 if (getDataLayout().isBigEndian())
4933 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004934 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004935
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004936 // Return in the smallest viable integer type.
4937 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004938 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004939 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004940 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4941 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004942 }
4943
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004944 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004945}
4946
Manman Renfef9e312012-10-16 19:18:39 +00004947/// isIllegalVector - check whether Ty is an illegal vector type.
4948bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4949 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4950 // Check whether VT is legal.
4951 unsigned NumElements = VT->getNumElements();
4952 uint64_t Size = getContext().getTypeSize(VT);
4953 // NumElements should be power of 2.
4954 if ((NumElements & (NumElements - 1)) != 0)
4955 return true;
4956 // Size should be greater than 32 bits.
4957 return Size <= 32;
4958 }
4959 return false;
4960}
4961
Reid Klecknere9f6a712014-10-31 17:10:41 +00004962bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4963 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4964 // double, or 64-bit or 128-bit vectors.
4965 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4966 if (BT->getKind() == BuiltinType::Float ||
4967 BT->getKind() == BuiltinType::Double ||
4968 BT->getKind() == BuiltinType::LongDouble)
4969 return true;
4970 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4971 unsigned VecSize = getContext().getTypeSize(VT);
4972 if (VecSize == 64 || VecSize == 128)
4973 return true;
4974 }
4975 return false;
4976}
4977
4978bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4979 uint64_t Members) const {
4980 return Members <= 4;
4981}
4982
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004983llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004984 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004985 llvm::Type *BP = CGF.Int8PtrTy;
4986 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004987
4988 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004989 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004990 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004991
Tim Northover1711cc92013-06-21 23:05:33 +00004992 if (isEmptyRecord(getContext(), Ty, true)) {
4993 // These are ignored for parameter passing purposes.
4994 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4995 return Builder.CreateBitCast(Addr, PTy);
4996 }
4997
Manman Rencca54d02012-10-16 19:01:37 +00004998 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004999 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00005000 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00005001
5002 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5003 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00005004 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5005 getABIKind() == ARMABIInfo::AAPCS)
5006 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5007 else
5008 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00005009 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5010 if (isIllegalVectorType(Ty) && Size > 16) {
5011 IsIndirect = true;
5012 Size = 4;
5013 TyAlign = 4;
5014 }
Manman Rencca54d02012-10-16 19:01:37 +00005015
5016 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005017 if (TyAlign > 4) {
5018 assert((TyAlign & (TyAlign - 1)) == 0 &&
5019 "Alignment is not power of 2!");
5020 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5021 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5022 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005023 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005024 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005025
5026 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005027 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005028 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005029 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005030 "ap.next");
5031 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5032
Manman Renfef9e312012-10-16 19:18:39 +00005033 if (IsIndirect)
5034 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005035 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005036 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5037 // may not be correctly aligned for the vector type. We create an aligned
5038 // temporary space and copy the content over from ap.cur to the temporary
5039 // space. This is necessary if the natural alignment of the type is greater
5040 // than the ABI alignment.
5041 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5042 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5043 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5044 "var.align");
5045 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5046 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5047 Builder.CreateMemCpy(Dst, Src,
5048 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5049 TyAlign, false);
5050 Addr = AlignedTemp; //The content is in aligned location.
5051 }
5052 llvm::Type *PTy =
5053 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5054 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5055
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005056 return AddrTyped;
5057}
5058
Chris Lattner0cf24192010-06-28 20:05:43 +00005059//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005060// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005061//===----------------------------------------------------------------------===//
5062
5063namespace {
5064
Justin Holewinski83e96682012-05-24 17:43:12 +00005065class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005066public:
Justin Holewinski36837432013-03-30 14:38:24 +00005067 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005068
5069 ABIArgInfo classifyReturnType(QualType RetTy) const;
5070 ABIArgInfo classifyArgumentType(QualType Ty) const;
5071
Craig Topper4f12f102014-03-12 06:41:41 +00005072 void computeInfo(CGFunctionInfo &FI) const override;
5073 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5074 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005075};
5076
Justin Holewinski83e96682012-05-24 17:43:12 +00005077class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005078public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005079 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5080 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005081
Eric Christopher162c91c2015-06-05 22:03:00 +00005082 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005083 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005084private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005085 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5086 // resulting MDNode to the nvvm.annotations MDNode.
5087 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005088};
5089
Justin Holewinski83e96682012-05-24 17:43:12 +00005090ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005091 if (RetTy->isVoidType())
5092 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005093
5094 // note: this is different from default ABI
5095 if (!RetTy->isScalarType())
5096 return ABIArgInfo::getDirect();
5097
5098 // Treat an enum type as its underlying type.
5099 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5100 RetTy = EnumTy->getDecl()->getIntegerType();
5101
5102 return (RetTy->isPromotableIntegerType() ?
5103 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005104}
5105
Justin Holewinski83e96682012-05-24 17:43:12 +00005106ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005107 // Treat an enum type as its underlying type.
5108 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5109 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005110
Eli Bendersky95338a02014-10-29 13:43:21 +00005111 // Return aggregates type as indirect by value
5112 if (isAggregateTypeForABI(Ty))
5113 return ABIArgInfo::getIndirect(0, /* byval */ true);
5114
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005115 return (Ty->isPromotableIntegerType() ?
5116 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005117}
5118
Justin Holewinski83e96682012-05-24 17:43:12 +00005119void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005120 if (!getCXXABI().classifyReturnType(FI))
5121 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005122 for (auto &I : FI.arguments())
5123 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005124
5125 // Always honor user-specified calling convention.
5126 if (FI.getCallingConvention() != llvm::CallingConv::C)
5127 return;
5128
John McCall882987f2013-02-28 19:01:20 +00005129 FI.setEffectiveCallingConvention(getRuntimeCC());
5130}
5131
Justin Holewinski83e96682012-05-24 17:43:12 +00005132llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5133 CodeGenFunction &CFG) const {
5134 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005135}
5136
Justin Holewinski83e96682012-05-24 17:43:12 +00005137void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005138setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005139 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005140 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5141 if (!FD) return;
5142
5143 llvm::Function *F = cast<llvm::Function>(GV);
5144
5145 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005146 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005147 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005148 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005149 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005150 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005151 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5152 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005153 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005154 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005155 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005156 }
Justin Holewinski38031972011-10-05 17:58:44 +00005157
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005158 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005159 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005160 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005161 // __global__ functions cannot be called from the device, we do not
5162 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005163 if (FD->hasAttr<CUDAGlobalAttr>()) {
5164 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5165 addNVVMMetadata(F, "kernel", 1);
5166 }
Artem Belevich7093e402015-04-21 22:55:54 +00005167 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005168 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005169 llvm::APSInt MaxThreads(32);
5170 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5171 if (MaxThreads > 0)
5172 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5173
5174 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5175 // not specified in __launch_bounds__ or if the user specified a 0 value,
5176 // we don't have to add a PTX directive.
5177 if (Attr->getMinBlocks()) {
5178 llvm::APSInt MinBlocks(32);
5179 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5180 if (MinBlocks > 0)
5181 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5182 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005183 }
5184 }
Justin Holewinski38031972011-10-05 17:58:44 +00005185 }
5186}
5187
Eli Benderskye06a2c42014-04-15 16:57:05 +00005188void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5189 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005190 llvm::Module *M = F->getParent();
5191 llvm::LLVMContext &Ctx = M->getContext();
5192
5193 // Get "nvvm.annotations" metadata node
5194 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5195
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005196 llvm::Metadata *MDVals[] = {
5197 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5198 llvm::ConstantAsMetadata::get(
5199 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005200 // Append metadata to nvvm.annotations
5201 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5202}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005203}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005204
5205//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005206// SystemZ ABI Implementation
5207//===----------------------------------------------------------------------===//
5208
5209namespace {
5210
5211class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005212 bool HasVector;
5213
Ulrich Weigand47445072013-05-06 16:26:41 +00005214public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005215 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5216 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005217
5218 bool isPromotableIntegerType(QualType Ty) const;
5219 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005220 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005221 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005222 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005223
5224 ABIArgInfo classifyReturnType(QualType RetTy) const;
5225 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5226
Craig Topper4f12f102014-03-12 06:41:41 +00005227 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005228 if (!getCXXABI().classifyReturnType(FI))
5229 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005230 for (auto &I : FI.arguments())
5231 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005232 }
5233
Craig Topper4f12f102014-03-12 06:41:41 +00005234 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5235 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005236};
5237
5238class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5239public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005240 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5241 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005242};
5243
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005244}
Ulrich Weigand47445072013-05-06 16:26:41 +00005245
5246bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5247 // Treat an enum type as its underlying type.
5248 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5249 Ty = EnumTy->getDecl()->getIntegerType();
5250
5251 // Promotable integer types are required to be promoted by the ABI.
5252 if (Ty->isPromotableIntegerType())
5253 return true;
5254
5255 // 32-bit values must also be promoted.
5256 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5257 switch (BT->getKind()) {
5258 case BuiltinType::Int:
5259 case BuiltinType::UInt:
5260 return true;
5261 default:
5262 return false;
5263 }
5264 return false;
5265}
5266
5267bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005268 return (Ty->isAnyComplexType() ||
5269 Ty->isVectorType() ||
5270 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005271}
5272
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005273bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5274 return (HasVector &&
5275 Ty->isVectorType() &&
5276 getContext().getTypeSize(Ty) <= 128);
5277}
5278
Ulrich Weigand47445072013-05-06 16:26:41 +00005279bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5280 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5281 switch (BT->getKind()) {
5282 case BuiltinType::Float:
5283 case BuiltinType::Double:
5284 return true;
5285 default:
5286 return false;
5287 }
5288
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005289 return false;
5290}
5291
5292QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005293 if (const RecordType *RT = Ty->getAsStructureType()) {
5294 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005295 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005296
5297 // If this is a C++ record, check the bases first.
5298 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005299 for (const auto &I : CXXRD->bases()) {
5300 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005301
5302 // Empty bases don't affect things either way.
5303 if (isEmptyRecord(getContext(), Base, true))
5304 continue;
5305
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005306 if (!Found.isNull())
5307 return Ty;
5308 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005309 }
5310
5311 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005312 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005313 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005314 // Unlike isSingleElementStruct(), empty structure and array fields
5315 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005316 if (getContext().getLangOpts().CPlusPlus &&
5317 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5318 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005319
5320 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005321 // Nested structures still do though.
5322 if (!Found.isNull())
5323 return Ty;
5324 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005325 }
5326
5327 // Unlike isSingleElementStruct(), trailing padding is allowed.
5328 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005329 if (!Found.isNull())
5330 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005331 }
5332
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005333 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005334}
5335
5336llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5337 CodeGenFunction &CGF) const {
5338 // Assume that va_list type is correct; should be pointer to LLVM type:
5339 // struct {
5340 // i64 __gpr;
5341 // i64 __fpr;
5342 // i8 *__overflow_arg_area;
5343 // i8 *__reg_save_area;
5344 // };
5345
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005346 // Every non-vector argument occupies 8 bytes and is passed by preference
5347 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5348 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005349 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005350 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5351 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005352 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005353 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005354 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005355 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005356 unsigned UnpaddedBitSize;
5357 if (IsIndirect) {
5358 APTy = llvm::PointerType::getUnqual(APTy);
5359 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005360 } else {
5361 if (AI.getCoerceToType())
5362 ArgTy = AI.getCoerceToType();
5363 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005364 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005365 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005366 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005367 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005368 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5369
5370 unsigned PaddedSize = PaddedBitSize / 8;
5371 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5372
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005373 llvm::Type *IndexTy = CGF.Int64Ty;
5374 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5375
5376 if (IsVector) {
5377 // Work out the address of a vector argument on the stack.
5378 // Vector arguments are always passed in the high bits of a
5379 // single (8 byte) or double (16 byte) stack slot.
5380 llvm::Value *OverflowArgAreaPtr =
5381 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5382 "overflow_arg_area_ptr");
5383 llvm::Value *OverflowArgArea =
5384 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5385 llvm::Value *MemAddr =
5386 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5387
5388 // Update overflow_arg_area_ptr pointer
5389 llvm::Value *NewOverflowArgArea =
5390 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5391 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5392
5393 return MemAddr;
5394 }
5395
Ulrich Weigand47445072013-05-06 16:26:41 +00005396 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5397 if (InFPRs) {
5398 MaxRegs = 4; // Maximum of 4 FPR arguments
5399 RegCountField = 1; // __fpr
5400 RegSaveIndex = 16; // save offset for f0
5401 RegPadding = 0; // floats are passed in the high bits of an FPR
5402 } else {
5403 MaxRegs = 5; // Maximum of 5 GPR arguments
5404 RegCountField = 0; // __gpr
5405 RegSaveIndex = 2; // save offset for r2
5406 RegPadding = Padding; // values are passed in the low bits of a GPR
5407 }
5408
David Blaikie2e804282015-04-05 22:47:07 +00005409 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5410 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005411 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005412 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5413 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005414 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005415
5416 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5417 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5418 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5419 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5420
5421 // Emit code to load the value if it was passed in registers.
5422 CGF.EmitBlock(InRegBlock);
5423
5424 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005425 llvm::Value *ScaledRegCount =
5426 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5427 llvm::Value *RegBase =
5428 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5429 llvm::Value *RegOffset =
5430 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5431 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005432 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005433 llvm::Value *RegSaveArea =
5434 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5435 llvm::Value *RawRegAddr =
5436 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5437 llvm::Value *RegAddr =
5438 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5439
5440 // Update the register count
5441 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5442 llvm::Value *NewRegCount =
5443 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5444 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5445 CGF.EmitBranch(ContBlock);
5446
5447 // Emit code to load the value if it was passed in memory.
5448 CGF.EmitBlock(InMemBlock);
5449
5450 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005451 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5452 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005453 llvm::Value *OverflowArgArea =
5454 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5455 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5456 llvm::Value *RawMemAddr =
5457 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5458 llvm::Value *MemAddr =
5459 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5460
5461 // Update overflow_arg_area_ptr pointer
5462 llvm::Value *NewOverflowArgArea =
5463 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5464 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5465 CGF.EmitBranch(ContBlock);
5466
5467 // Return the appropriate result.
5468 CGF.EmitBlock(ContBlock);
5469 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5470 ResAddr->addIncoming(RegAddr, InRegBlock);
5471 ResAddr->addIncoming(MemAddr, InMemBlock);
5472
5473 if (IsIndirect)
5474 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5475
5476 return ResAddr;
5477}
5478
Ulrich Weigand47445072013-05-06 16:26:41 +00005479ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5480 if (RetTy->isVoidType())
5481 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005482 if (isVectorArgumentType(RetTy))
5483 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005484 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5485 return ABIArgInfo::getIndirect(0);
5486 return (isPromotableIntegerType(RetTy) ?
5487 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5488}
5489
5490ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5491 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005492 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005493 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5494
5495 // Integers and enums are extended to full register width.
5496 if (isPromotableIntegerType(Ty))
5497 return ABIArgInfo::getExtend();
5498
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005499 // Handle vector types and vector-like structure types. Note that
5500 // as opposed to float-like structure types, we do not allow any
5501 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005502 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005503 QualType SingleElementTy = GetSingleElementType(Ty);
5504 if (isVectorArgumentType(SingleElementTy) &&
5505 getContext().getTypeSize(SingleElementTy) == Size)
5506 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5507
5508 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005509 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005510 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005511
5512 // Handle small structures.
5513 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5514 // Structures with flexible arrays have variable length, so really
5515 // fail the size test above.
5516 const RecordDecl *RD = RT->getDecl();
5517 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005518 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005519
5520 // The structure is passed as an unextended integer, a float, or a double.
5521 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005522 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005523 assert(Size == 32 || Size == 64);
5524 if (Size == 32)
5525 PassTy = llvm::Type::getFloatTy(getVMContext());
5526 else
5527 PassTy = llvm::Type::getDoubleTy(getVMContext());
5528 } else
5529 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5530 return ABIArgInfo::getDirect(PassTy);
5531 }
5532
5533 // Non-structure compounds are passed indirectly.
5534 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005535 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005536
Craig Topper8a13c412014-05-21 05:09:00 +00005537 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005538}
5539
5540//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005541// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005542//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005543
5544namespace {
5545
5546class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5547public:
Chris Lattner2b037972010-07-29 02:01:43 +00005548 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5549 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005550 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005551 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005552};
5553
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005554}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005555
Eric Christopher162c91c2015-06-05 22:03:00 +00005556void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005557 llvm::GlobalValue *GV,
5558 CodeGen::CodeGenModule &M) const {
5559 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5560 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5561 // Handle 'interrupt' attribute:
5562 llvm::Function *F = cast<llvm::Function>(GV);
5563
5564 // Step 1: Set ISR calling convention.
5565 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5566
5567 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005568 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005569
5570 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005571 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005572 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5573 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005574 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005575 }
5576}
5577
Chris Lattner0cf24192010-06-28 20:05:43 +00005578//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005579// MIPS ABI Implementation. This works for both little-endian and
5580// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005581//===----------------------------------------------------------------------===//
5582
John McCall943fae92010-05-27 06:19:26 +00005583namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005584class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005585 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005586 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5587 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005588 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005589 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005590 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005591 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005592public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005593 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005594 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005595 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005596
5597 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005598 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005599 void computeInfo(CGFunctionInfo &FI) const override;
5600 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5601 CodeGenFunction &CGF) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005602 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005603};
5604
John McCall943fae92010-05-27 06:19:26 +00005605class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005606 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005607public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005608 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5609 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005610 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005611
Craig Topper4f12f102014-03-12 06:41:41 +00005612 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005613 return 29;
5614 }
5615
Eric Christopher162c91c2015-06-05 22:03:00 +00005616 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005617 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005618 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5619 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005620 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005621 if (FD->hasAttr<Mips16Attr>()) {
5622 Fn->addFnAttr("mips16");
5623 }
5624 else if (FD->hasAttr<NoMips16Attr>()) {
5625 Fn->addFnAttr("nomips16");
5626 }
Reed Kotler373feca2013-01-16 17:10:28 +00005627 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005628
John McCall943fae92010-05-27 06:19:26 +00005629 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005630 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005631
Craig Topper4f12f102014-03-12 06:41:41 +00005632 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005633 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005634 }
John McCall943fae92010-05-27 06:19:26 +00005635};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005636}
John McCall943fae92010-05-27 06:19:26 +00005637
Eric Christopher7565e0d2015-05-29 23:09:49 +00005638void MipsABIInfo::CoerceToIntArgs(
5639 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005640 llvm::IntegerType *IntTy =
5641 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005642
5643 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5644 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5645 ArgList.push_back(IntTy);
5646
5647 // If necessary, add one more integer type to ArgList.
5648 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5649
5650 if (R)
5651 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005652}
5653
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005654// In N32/64, an aligned double precision floating point field is passed in
5655// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005656llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005657 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5658
5659 if (IsO32) {
5660 CoerceToIntArgs(TySize, ArgList);
5661 return llvm::StructType::get(getVMContext(), ArgList);
5662 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005663
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005664 if (Ty->isComplexType())
5665 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005666
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005667 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005668
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005669 // Unions/vectors are passed in integer registers.
5670 if (!RT || !RT->isStructureOrClassType()) {
5671 CoerceToIntArgs(TySize, ArgList);
5672 return llvm::StructType::get(getVMContext(), ArgList);
5673 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005674
5675 const RecordDecl *RD = RT->getDecl();
5676 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005677 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005678
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005679 uint64_t LastOffset = 0;
5680 unsigned idx = 0;
5681 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5682
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005683 // Iterate over fields in the struct/class and check if there are any aligned
5684 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005685 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5686 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005687 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005688 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5689
5690 if (!BT || BT->getKind() != BuiltinType::Double)
5691 continue;
5692
5693 uint64_t Offset = Layout.getFieldOffset(idx);
5694 if (Offset % 64) // Ignore doubles that are not aligned.
5695 continue;
5696
5697 // Add ((Offset - LastOffset) / 64) args of type i64.
5698 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5699 ArgList.push_back(I64);
5700
5701 // Add double type.
5702 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5703 LastOffset = Offset + 64;
5704 }
5705
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005706 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5707 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005708
5709 return llvm::StructType::get(getVMContext(), ArgList);
5710}
5711
Akira Hatanakaddd66342013-10-29 18:41:15 +00005712llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5713 uint64_t Offset) const {
5714 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005715 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005716
Akira Hatanakaddd66342013-10-29 18:41:15 +00005717 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005718}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005719
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005720ABIArgInfo
5721MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005722 Ty = useFirstFieldIfTransparentUnion(Ty);
5723
Akira Hatanaka1632af62012-01-09 19:31:25 +00005724 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005725 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005726 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005727
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005728 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5729 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005730 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5731 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005732
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005733 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005734 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005735 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005736 return ABIArgInfo::getIgnore();
5737
Mark Lacey3825e832013-10-06 01:33:34 +00005738 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005739 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005740 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005741 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005742
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005743 // If we have reached here, aggregates are passed directly by coercing to
5744 // another structure type. Padding is inserted if the offset of the
5745 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005746 ABIArgInfo ArgInfo =
5747 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5748 getPaddingType(OrigOffset, CurrOffset));
5749 ArgInfo.setInReg(true);
5750 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005751 }
5752
5753 // Treat an enum type as its underlying type.
5754 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5755 Ty = EnumTy->getDecl()->getIntegerType();
5756
Daniel Sanders5b445b32014-10-24 14:42:42 +00005757 // All integral types are promoted to the GPR width.
5758 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005759 return ABIArgInfo::getExtend();
5760
Akira Hatanakaddd66342013-10-29 18:41:15 +00005761 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005762 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005763}
5764
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005765llvm::Type*
5766MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005767 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005768 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005769
Akira Hatanakab6f74432012-02-09 18:49:26 +00005770 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005771 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005772 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5773 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005774
Akira Hatanakab6f74432012-02-09 18:49:26 +00005775 // N32/64 returns struct/classes in floating point registers if the
5776 // following conditions are met:
5777 // 1. The size of the struct/class is no larger than 128-bit.
5778 // 2. The struct/class has one or two fields all of which are floating
5779 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005780 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005781 //
5782 // Any other composite results are returned in integer registers.
5783 //
5784 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5785 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5786 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005787 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005788
Akira Hatanakab6f74432012-02-09 18:49:26 +00005789 if (!BT || !BT->isFloatingPoint())
5790 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005791
David Blaikie2d7c57e2012-04-30 02:36:29 +00005792 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005793 }
5794
5795 if (b == e)
5796 return llvm::StructType::get(getVMContext(), RTList,
5797 RD->hasAttr<PackedAttr>());
5798
5799 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005800 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005801 }
5802
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005803 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005804 return llvm::StructType::get(getVMContext(), RTList);
5805}
5806
Akira Hatanakab579fe52011-06-02 00:09:17 +00005807ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005808 uint64_t Size = getContext().getTypeSize(RetTy);
5809
Daniel Sandersed39f582014-09-04 13:28:14 +00005810 if (RetTy->isVoidType())
5811 return ABIArgInfo::getIgnore();
5812
5813 // O32 doesn't treat zero-sized structs differently from other structs.
5814 // However, N32/N64 ignores zero sized return values.
5815 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005816 return ABIArgInfo::getIgnore();
5817
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005818 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005819 if (Size <= 128) {
5820 if (RetTy->isAnyComplexType())
5821 return ABIArgInfo::getDirect();
5822
Daniel Sanderse5018b62014-09-04 15:05:39 +00005823 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005824 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005825 if (!IsO32 ||
5826 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5827 ABIArgInfo ArgInfo =
5828 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5829 ArgInfo.setInReg(true);
5830 return ArgInfo;
5831 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005832 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005833
5834 return ABIArgInfo::getIndirect(0);
5835 }
5836
5837 // Treat an enum type as its underlying type.
5838 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5839 RetTy = EnumTy->getDecl()->getIntegerType();
5840
5841 return (RetTy->isPromotableIntegerType() ?
5842 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5843}
5844
5845void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005846 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005847 if (!getCXXABI().classifyReturnType(FI))
5848 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005849
Eric Christopher7565e0d2015-05-29 23:09:49 +00005850 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005851 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005852
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005853 for (auto &I : FI.arguments())
5854 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005855}
5856
5857llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5858 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005859 llvm::Type *BP = CGF.Int8PtrTy;
5860 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005861
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005862 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5863 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005864 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005865 unsigned PtrWidth = getTarget().getPointerWidth(0);
5866 if ((Ty->isIntegerType() &&
5867 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5868 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005869 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5870 Ty->isSignedIntegerType());
5871 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00005872
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005873 CGBuilderTy &Builder = CGF.Builder;
5874 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5875 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005876 int64_t TypeAlign =
5877 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005878 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5879 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005880 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5881
5882 if (TypeAlign > MinABIStackAlignInBytes) {
5883 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5884 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5885 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5886 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5887 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5888 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5889 }
5890 else
Eric Christopher7565e0d2015-05-29 23:09:49 +00005891 AddrTyped = Builder.CreateBitCast(Addr, PTy);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005892
5893 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5894 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005895 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5896 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005897 llvm::Value *NextAddr =
5898 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5899 "ap.next");
5900 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005901
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005902 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005903}
5904
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005905bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
5906 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005907
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005908 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
5909 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
5910 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00005911
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005912 return false;
5913}
5914
John McCall943fae92010-05-27 06:19:26 +00005915bool
5916MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5917 llvm::Value *Address) const {
5918 // This information comes from gcc's implementation, which seems to
5919 // as canonical as it gets.
5920
John McCall943fae92010-05-27 06:19:26 +00005921 // Everything on MIPS is 4 bytes. Double-precision FP registers
5922 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005923 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005924
5925 // 0-31 are the general purpose registers, $0 - $31.
5926 // 32-63 are the floating-point registers, $f0 - $f31.
5927 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5928 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005929 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005930
5931 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5932 // They are one bit wide and ignored here.
5933
5934 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5935 // (coprocessor 1 is the FP unit)
5936 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5937 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5938 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005939 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005940 return false;
5941}
5942
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005943//===----------------------------------------------------------------------===//
5944// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005945// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005946// handling.
5947//===----------------------------------------------------------------------===//
5948
5949namespace {
5950
5951class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5952public:
5953 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5954 : DefaultTargetCodeGenInfo(CGT) {}
5955
Eric Christopher162c91c2015-06-05 22:03:00 +00005956 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005957 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005958};
5959
Eric Christopher162c91c2015-06-05 22:03:00 +00005960void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00005961 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005962 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5963 if (!FD) return;
5964
5965 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005966
David Blaikiebbafb8a2012-03-11 07:00:24 +00005967 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005968 if (FD->hasAttr<OpenCLKernelAttr>()) {
5969 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005970 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005971 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5972 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005973 // Convert the reqd_work_group_size() attributes to metadata.
5974 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00005975 llvm::NamedMDNode *OpenCLMetadata =
5976 M.getModule().getOrInsertNamedMetadata(
5977 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005978
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005979 SmallVector<llvm::Metadata *, 5> Operands;
5980 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005981
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005982 Operands.push_back(
5983 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5984 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5985 Operands.push_back(
5986 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5987 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5988 Operands.push_back(
5989 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5990 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005991
Eric Christopher7565e0d2015-05-29 23:09:49 +00005992 // Add a boolean constant operand for "required" (true) or "hint"
5993 // (false) for implementing the work_group_size_hint attr later.
5994 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005995 Operands.push_back(
5996 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005997 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5998 }
5999 }
6000 }
6001}
6002
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006003}
John McCall943fae92010-05-27 06:19:26 +00006004
Tony Linthicum76329bf2011-12-12 21:14:55 +00006005//===----------------------------------------------------------------------===//
6006// Hexagon ABI Implementation
6007//===----------------------------------------------------------------------===//
6008
6009namespace {
6010
6011class HexagonABIInfo : public ABIInfo {
6012
6013
6014public:
6015 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6016
6017private:
6018
6019 ABIArgInfo classifyReturnType(QualType RetTy) const;
6020 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6021
Craig Topper4f12f102014-03-12 06:41:41 +00006022 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006023
Craig Topper4f12f102014-03-12 06:41:41 +00006024 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6025 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006026};
6027
6028class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6029public:
6030 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6031 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6032
Craig Topper4f12f102014-03-12 06:41:41 +00006033 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006034 return 29;
6035 }
6036};
6037
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006038}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006039
6040void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006041 if (!getCXXABI().classifyReturnType(FI))
6042 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006043 for (auto &I : FI.arguments())
6044 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006045}
6046
6047ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6048 if (!isAggregateTypeForABI(Ty)) {
6049 // Treat an enum type as its underlying type.
6050 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6051 Ty = EnumTy->getDecl()->getIntegerType();
6052
6053 return (Ty->isPromotableIntegerType() ?
6054 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6055 }
6056
6057 // Ignore empty records.
6058 if (isEmptyRecord(getContext(), Ty, true))
6059 return ABIArgInfo::getIgnore();
6060
Mark Lacey3825e832013-10-06 01:33:34 +00006061 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006062 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006063
6064 uint64_t Size = getContext().getTypeSize(Ty);
6065 if (Size > 64)
6066 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6067 // Pass in the smallest viable integer type.
6068 else if (Size > 32)
6069 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6070 else if (Size > 16)
6071 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6072 else if (Size > 8)
6073 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6074 else
6075 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6076}
6077
6078ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6079 if (RetTy->isVoidType())
6080 return ABIArgInfo::getIgnore();
6081
6082 // Large vector types should be returned via memory.
6083 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6084 return ABIArgInfo::getIndirect(0);
6085
6086 if (!isAggregateTypeForABI(RetTy)) {
6087 // Treat an enum type as its underlying type.
6088 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6089 RetTy = EnumTy->getDecl()->getIntegerType();
6090
6091 return (RetTy->isPromotableIntegerType() ?
6092 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6093 }
6094
Tony Linthicum76329bf2011-12-12 21:14:55 +00006095 if (isEmptyRecord(getContext(), RetTy, true))
6096 return ABIArgInfo::getIgnore();
6097
6098 // Aggregates <= 8 bytes are returned in r0; other aggregates
6099 // are returned indirectly.
6100 uint64_t Size = getContext().getTypeSize(RetTy);
6101 if (Size <= 64) {
6102 // Return in the smallest viable integer type.
6103 if (Size <= 8)
6104 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6105 if (Size <= 16)
6106 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6107 if (Size <= 32)
6108 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6109 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6110 }
6111
6112 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6113}
6114
6115llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006116 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006117 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006118 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006119
6120 CGBuilderTy &Builder = CGF.Builder;
6121 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6122 "ap");
6123 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6124 llvm::Type *PTy =
6125 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6126 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6127
6128 uint64_t Offset =
6129 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6130 llvm::Value *NextAddr =
6131 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6132 "ap.next");
6133 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6134
6135 return AddrTyped;
6136}
6137
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006138//===----------------------------------------------------------------------===//
6139// AMDGPU ABI Implementation
6140//===----------------------------------------------------------------------===//
6141
6142namespace {
6143
6144class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6145public:
6146 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6147 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006148 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006149 CodeGen::CodeGenModule &M) const override;
6150};
6151
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006152}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006153
Eric Christopher162c91c2015-06-05 22:03:00 +00006154void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006155 const Decl *D,
6156 llvm::GlobalValue *GV,
6157 CodeGen::CodeGenModule &M) const {
6158 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6159 if (!FD)
6160 return;
6161
6162 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6163 llvm::Function *F = cast<llvm::Function>(GV);
6164 uint32_t NumVGPR = Attr->getNumVGPR();
6165 if (NumVGPR != 0)
6166 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6167 }
6168
6169 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6170 llvm::Function *F = cast<llvm::Function>(GV);
6171 unsigned NumSGPR = Attr->getNumSGPR();
6172 if (NumSGPR != 0)
6173 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6174 }
6175}
6176
Tony Linthicum76329bf2011-12-12 21:14:55 +00006177
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006178//===----------------------------------------------------------------------===//
6179// SPARC v9 ABI Implementation.
6180// Based on the SPARC Compliance Definition version 2.4.1.
6181//
6182// Function arguments a mapped to a nominal "parameter array" and promoted to
6183// registers depending on their type. Each argument occupies 8 or 16 bytes in
6184// the array, structs larger than 16 bytes are passed indirectly.
6185//
6186// One case requires special care:
6187//
6188// struct mixed {
6189// int i;
6190// float f;
6191// };
6192//
6193// When a struct mixed is passed by value, it only occupies 8 bytes in the
6194// parameter array, but the int is passed in an integer register, and the float
6195// is passed in a floating point register. This is represented as two arguments
6196// with the LLVM IR inreg attribute:
6197//
6198// declare void f(i32 inreg %i, float inreg %f)
6199//
6200// The code generator will only allocate 4 bytes from the parameter array for
6201// the inreg arguments. All other arguments are allocated a multiple of 8
6202// bytes.
6203//
6204namespace {
6205class SparcV9ABIInfo : public ABIInfo {
6206public:
6207 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6208
6209private:
6210 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006211 void computeInfo(CGFunctionInfo &FI) const override;
6212 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6213 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006214
6215 // Coercion type builder for structs passed in registers. The coercion type
6216 // serves two purposes:
6217 //
6218 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6219 // in registers.
6220 // 2. Expose aligned floating point elements as first-level elements, so the
6221 // code generator knows to pass them in floating point registers.
6222 //
6223 // We also compute the InReg flag which indicates that the struct contains
6224 // aligned 32-bit floats.
6225 //
6226 struct CoerceBuilder {
6227 llvm::LLVMContext &Context;
6228 const llvm::DataLayout &DL;
6229 SmallVector<llvm::Type*, 8> Elems;
6230 uint64_t Size;
6231 bool InReg;
6232
6233 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6234 : Context(c), DL(dl), Size(0), InReg(false) {}
6235
6236 // Pad Elems with integers until Size is ToSize.
6237 void pad(uint64_t ToSize) {
6238 assert(ToSize >= Size && "Cannot remove elements");
6239 if (ToSize == Size)
6240 return;
6241
6242 // Finish the current 64-bit word.
6243 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6244 if (Aligned > Size && Aligned <= ToSize) {
6245 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6246 Size = Aligned;
6247 }
6248
6249 // Add whole 64-bit words.
6250 while (Size + 64 <= ToSize) {
6251 Elems.push_back(llvm::Type::getInt64Ty(Context));
6252 Size += 64;
6253 }
6254
6255 // Final in-word padding.
6256 if (Size < ToSize) {
6257 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6258 Size = ToSize;
6259 }
6260 }
6261
6262 // Add a floating point element at Offset.
6263 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6264 // Unaligned floats are treated as integers.
6265 if (Offset % Bits)
6266 return;
6267 // The InReg flag is only required if there are any floats < 64 bits.
6268 if (Bits < 64)
6269 InReg = true;
6270 pad(Offset);
6271 Elems.push_back(Ty);
6272 Size = Offset + Bits;
6273 }
6274
6275 // Add a struct type to the coercion type, starting at Offset (in bits).
6276 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6277 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6278 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6279 llvm::Type *ElemTy = StrTy->getElementType(i);
6280 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6281 switch (ElemTy->getTypeID()) {
6282 case llvm::Type::StructTyID:
6283 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6284 break;
6285 case llvm::Type::FloatTyID:
6286 addFloat(ElemOffset, ElemTy, 32);
6287 break;
6288 case llvm::Type::DoubleTyID:
6289 addFloat(ElemOffset, ElemTy, 64);
6290 break;
6291 case llvm::Type::FP128TyID:
6292 addFloat(ElemOffset, ElemTy, 128);
6293 break;
6294 case llvm::Type::PointerTyID:
6295 if (ElemOffset % 64 == 0) {
6296 pad(ElemOffset);
6297 Elems.push_back(ElemTy);
6298 Size += 64;
6299 }
6300 break;
6301 default:
6302 break;
6303 }
6304 }
6305 }
6306
6307 // Check if Ty is a usable substitute for the coercion type.
6308 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006309 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006310 }
6311
6312 // Get the coercion type as a literal struct type.
6313 llvm::Type *getType() const {
6314 if (Elems.size() == 1)
6315 return Elems.front();
6316 else
6317 return llvm::StructType::get(Context, Elems);
6318 }
6319 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006320};
6321} // end anonymous namespace
6322
6323ABIArgInfo
6324SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6325 if (Ty->isVoidType())
6326 return ABIArgInfo::getIgnore();
6327
6328 uint64_t Size = getContext().getTypeSize(Ty);
6329
6330 // Anything too big to fit in registers is passed with an explicit indirect
6331 // pointer / sret pointer.
6332 if (Size > SizeLimit)
6333 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6334
6335 // Treat an enum type as its underlying type.
6336 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6337 Ty = EnumTy->getDecl()->getIntegerType();
6338
6339 // Integer types smaller than a register are extended.
6340 if (Size < 64 && Ty->isIntegerType())
6341 return ABIArgInfo::getExtend();
6342
6343 // Other non-aggregates go in registers.
6344 if (!isAggregateTypeForABI(Ty))
6345 return ABIArgInfo::getDirect();
6346
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006347 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6348 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6349 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6350 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6351
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006352 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006353 // Build a coercion type from the LLVM struct type.
6354 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6355 if (!StrTy)
6356 return ABIArgInfo::getDirect();
6357
6358 CoerceBuilder CB(getVMContext(), getDataLayout());
6359 CB.addStruct(0, StrTy);
6360 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6361
6362 // Try to use the original type for coercion.
6363 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6364
6365 if (CB.InReg)
6366 return ABIArgInfo::getDirectInReg(CoerceTy);
6367 else
6368 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006369}
6370
6371llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6372 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006373 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6374 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6375 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6376 AI.setCoerceToType(ArgTy);
6377
6378 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6379 CGBuilderTy &Builder = CGF.Builder;
6380 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6381 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6382 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6383 llvm::Value *ArgAddr;
6384 unsigned Stride;
6385
6386 switch (AI.getKind()) {
6387 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006388 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006389 llvm_unreachable("Unsupported ABI kind for va_arg");
6390
6391 case ABIArgInfo::Extend:
6392 Stride = 8;
6393 ArgAddr = Builder
6394 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6395 "extend");
6396 break;
6397
6398 case ABIArgInfo::Direct:
6399 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6400 ArgAddr = Addr;
6401 break;
6402
6403 case ABIArgInfo::Indirect:
6404 Stride = 8;
6405 ArgAddr = Builder.CreateBitCast(Addr,
6406 llvm::PointerType::getUnqual(ArgPtrTy),
6407 "indirect");
6408 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6409 break;
6410
6411 case ABIArgInfo::Ignore:
6412 return llvm::UndefValue::get(ArgPtrTy);
6413 }
6414
6415 // Update VAList.
6416 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6417 Builder.CreateStore(Addr, VAListAddrAsBPP);
6418
6419 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006420}
6421
6422void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6423 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006424 for (auto &I : FI.arguments())
6425 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006426}
6427
6428namespace {
6429class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6430public:
6431 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6432 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006433
Craig Topper4f12f102014-03-12 06:41:41 +00006434 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006435 return 14;
6436 }
6437
6438 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006439 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006440};
6441} // end anonymous namespace
6442
Roman Divackyf02c9942014-02-24 18:46:27 +00006443bool
6444SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6445 llvm::Value *Address) const {
6446 // This is calculated from the LLVM and GCC tables and verified
6447 // against gcc output. AFAIK all ABIs use the same encoding.
6448
6449 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6450
6451 llvm::IntegerType *i8 = CGF.Int8Ty;
6452 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6453 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6454
6455 // 0-31: the 8-byte general-purpose registers
6456 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6457
6458 // 32-63: f0-31, the 4-byte floating-point registers
6459 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6460
6461 // Y = 64
6462 // PSR = 65
6463 // WIM = 66
6464 // TBR = 67
6465 // PC = 68
6466 // NPC = 69
6467 // FSR = 70
6468 // CSR = 71
6469 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006470
Roman Divackyf02c9942014-02-24 18:46:27 +00006471 // 72-87: d0-15, the 8-byte floating-point registers
6472 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6473
6474 return false;
6475}
6476
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006477
Robert Lytton0e076492013-08-13 09:43:10 +00006478//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006479// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006480//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006481
Robert Lytton0e076492013-08-13 09:43:10 +00006482namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006483
6484/// A SmallStringEnc instance is used to build up the TypeString by passing
6485/// it by reference between functions that append to it.
6486typedef llvm::SmallString<128> SmallStringEnc;
6487
6488/// TypeStringCache caches the meta encodings of Types.
6489///
6490/// The reason for caching TypeStrings is two fold:
6491/// 1. To cache a type's encoding for later uses;
6492/// 2. As a means to break recursive member type inclusion.
6493///
6494/// A cache Entry can have a Status of:
6495/// NonRecursive: The type encoding is not recursive;
6496/// Recursive: The type encoding is recursive;
6497/// Incomplete: An incomplete TypeString;
6498/// IncompleteUsed: An incomplete TypeString that has been used in a
6499/// Recursive type encoding.
6500///
6501/// A NonRecursive entry will have all of its sub-members expanded as fully
6502/// as possible. Whilst it may contain types which are recursive, the type
6503/// itself is not recursive and thus its encoding may be safely used whenever
6504/// the type is encountered.
6505///
6506/// A Recursive entry will have all of its sub-members expanded as fully as
6507/// possible. The type itself is recursive and it may contain other types which
6508/// are recursive. The Recursive encoding must not be used during the expansion
6509/// of a recursive type's recursive branch. For simplicity the code uses
6510/// IncompleteCount to reject all usage of Recursive encodings for member types.
6511///
6512/// An Incomplete entry is always a RecordType and only encodes its
6513/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6514/// are placed into the cache during type expansion as a means to identify and
6515/// handle recursive inclusion of types as sub-members. If there is recursion
6516/// the entry becomes IncompleteUsed.
6517///
6518/// During the expansion of a RecordType's members:
6519///
6520/// If the cache contains a NonRecursive encoding for the member type, the
6521/// cached encoding is used;
6522///
6523/// If the cache contains a Recursive encoding for the member type, the
6524/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6525///
6526/// If the member is a RecordType, an Incomplete encoding is placed into the
6527/// cache to break potential recursive inclusion of itself as a sub-member;
6528///
6529/// Once a member RecordType has been expanded, its temporary incomplete
6530/// entry is removed from the cache. If a Recursive encoding was swapped out
6531/// it is swapped back in;
6532///
6533/// If an incomplete entry is used to expand a sub-member, the incomplete
6534/// entry is marked as IncompleteUsed. The cache keeps count of how many
6535/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6536///
6537/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6538/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6539/// Else the member is part of a recursive type and thus the recursion has
6540/// been exited too soon for the encoding to be correct for the member.
6541///
6542class TypeStringCache {
6543 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6544 struct Entry {
6545 std::string Str; // The encoded TypeString for the type.
6546 enum Status State; // Information about the encoding in 'Str'.
6547 std::string Swapped; // A temporary place holder for a Recursive encoding
6548 // during the expansion of RecordType's members.
6549 };
6550 std::map<const IdentifierInfo *, struct Entry> Map;
6551 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6552 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6553public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006554 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006555 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6556 bool removeIncomplete(const IdentifierInfo *ID);
6557 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6558 bool IsRecursive);
6559 StringRef lookupStr(const IdentifierInfo *ID);
6560};
6561
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006562/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006563/// FieldEncoding is a helper for this ordering process.
6564class FieldEncoding {
6565 bool HasName;
6566 std::string Enc;
6567public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006568 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6569 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006570 bool operator<(const FieldEncoding &rhs) const {
6571 if (HasName != rhs.HasName) return HasName;
6572 return Enc < rhs.Enc;
6573 }
6574};
6575
Robert Lytton7d1db152013-08-19 09:46:39 +00006576class XCoreABIInfo : public DefaultABIInfo {
6577public:
6578 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006579 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6580 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006581};
6582
Robert Lyttond21e2d72014-03-03 13:45:29 +00006583class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006584 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006585public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006586 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006587 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006588 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6589 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006590};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006591
Robert Lytton2d196952013-10-11 10:29:34 +00006592} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006593
Robert Lytton7d1db152013-08-19 09:46:39 +00006594llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6595 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006596 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006597
Robert Lytton2d196952013-10-11 10:29:34 +00006598 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006599 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6600 CGF.Int8PtrPtrTy);
6601 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006602
Robert Lytton2d196952013-10-11 10:29:34 +00006603 // Handle the argument.
6604 ABIArgInfo AI = classifyArgumentType(Ty);
6605 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6606 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6607 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006608 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006609 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006610 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006611 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006612 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006613 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006614 llvm_unreachable("Unsupported ABI kind for va_arg");
6615 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006616 Val = llvm::UndefValue::get(ArgPtrTy);
6617 ArgSize = 0;
6618 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006619 case ABIArgInfo::Extend:
6620 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006621 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6622 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6623 if (ArgSize < 4)
6624 ArgSize = 4;
6625 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006626 case ABIArgInfo::Indirect:
6627 llvm::Value *ArgAddr;
6628 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6629 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006630 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6631 ArgSize = 4;
6632 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006633 }
Robert Lytton2d196952013-10-11 10:29:34 +00006634
6635 // Increment the VAList.
6636 if (ArgSize) {
6637 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6638 Builder.CreateStore(APN, VAListAddrAsBPP);
6639 }
6640 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006641}
Robert Lytton0e076492013-08-13 09:43:10 +00006642
Robert Lytton844aeeb2014-05-02 09:33:20 +00006643/// During the expansion of a RecordType, an incomplete TypeString is placed
6644/// into the cache as a means to identify and break recursion.
6645/// If there is a Recursive encoding in the cache, it is swapped out and will
6646/// be reinserted by removeIncomplete().
6647/// All other types of encoding should have been used rather than arriving here.
6648void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6649 std::string StubEnc) {
6650 if (!ID)
6651 return;
6652 Entry &E = Map[ID];
6653 assert( (E.Str.empty() || E.State == Recursive) &&
6654 "Incorrectly use of addIncomplete");
6655 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6656 E.Swapped.swap(E.Str); // swap out the Recursive
6657 E.Str.swap(StubEnc);
6658 E.State = Incomplete;
6659 ++IncompleteCount;
6660}
6661
6662/// Once the RecordType has been expanded, the temporary incomplete TypeString
6663/// must be removed from the cache.
6664/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6665/// Returns true if the RecordType was defined recursively.
6666bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6667 if (!ID)
6668 return false;
6669 auto I = Map.find(ID);
6670 assert(I != Map.end() && "Entry not present");
6671 Entry &E = I->second;
6672 assert( (E.State == Incomplete ||
6673 E.State == IncompleteUsed) &&
6674 "Entry must be an incomplete type");
6675 bool IsRecursive = false;
6676 if (E.State == IncompleteUsed) {
6677 // We made use of our Incomplete encoding, thus we are recursive.
6678 IsRecursive = true;
6679 --IncompleteUsedCount;
6680 }
6681 if (E.Swapped.empty())
6682 Map.erase(I);
6683 else {
6684 // Swap the Recursive back.
6685 E.Swapped.swap(E.Str);
6686 E.Swapped.clear();
6687 E.State = Recursive;
6688 }
6689 --IncompleteCount;
6690 return IsRecursive;
6691}
6692
6693/// Add the encoded TypeString to the cache only if it is NonRecursive or
6694/// Recursive (viz: all sub-members were expanded as fully as possible).
6695void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6696 bool IsRecursive) {
6697 if (!ID || IncompleteUsedCount)
6698 return; // No key or it is is an incomplete sub-type so don't add.
6699 Entry &E = Map[ID];
6700 if (IsRecursive && !E.Str.empty()) {
6701 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6702 "This is not the same Recursive entry");
6703 // The parent container was not recursive after all, so we could have used
6704 // this Recursive sub-member entry after all, but we assumed the worse when
6705 // we started viz: IncompleteCount!=0.
6706 return;
6707 }
6708 assert(E.Str.empty() && "Entry already present");
6709 E.Str = Str.str();
6710 E.State = IsRecursive? Recursive : NonRecursive;
6711}
6712
6713/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6714/// are recursively expanding a type (IncompleteCount != 0) and the cached
6715/// encoding is Recursive, return an empty StringRef.
6716StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6717 if (!ID)
6718 return StringRef(); // We have no key.
6719 auto I = Map.find(ID);
6720 if (I == Map.end())
6721 return StringRef(); // We have no encoding.
6722 Entry &E = I->second;
6723 if (E.State == Recursive && IncompleteCount)
6724 return StringRef(); // We don't use Recursive encodings for member types.
6725
6726 if (E.State == Incomplete) {
6727 // The incomplete type is being used to break out of recursion.
6728 E.State = IncompleteUsed;
6729 ++IncompleteUsedCount;
6730 }
6731 return E.Str.c_str();
6732}
6733
6734/// The XCore ABI includes a type information section that communicates symbol
6735/// type information to the linker. The linker uses this information to verify
6736/// safety/correctness of things such as array bound and pointers et al.
6737/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6738/// This type information (TypeString) is emitted into meta data for all global
6739/// symbols: definitions, declarations, functions & variables.
6740///
6741/// The TypeString carries type, qualifier, name, size & value details.
6742/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006743/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006744/// The output is tested by test/CodeGen/xcore-stringtype.c.
6745///
6746static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6747 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6748
6749/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6750void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6751 CodeGen::CodeGenModule &CGM) const {
6752 SmallStringEnc Enc;
6753 if (getTypeString(Enc, D, CGM, TSC)) {
6754 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006755 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6756 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006757 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6758 llvm::NamedMDNode *MD =
6759 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6760 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6761 }
6762}
6763
6764static bool appendType(SmallStringEnc &Enc, QualType QType,
6765 const CodeGen::CodeGenModule &CGM,
6766 TypeStringCache &TSC);
6767
6768/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006769/// Builds a SmallVector containing the encoded field types in declaration
6770/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006771static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6772 const RecordDecl *RD,
6773 const CodeGen::CodeGenModule &CGM,
6774 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006775 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006776 SmallStringEnc Enc;
6777 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006778 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006779 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006780 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006781 Enc += "b(";
6782 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00006783 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006784 Enc += ':';
6785 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006786 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006787 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006788 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006789 Enc += ')';
6790 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00006791 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006792 }
6793 return true;
6794}
6795
6796/// Appends structure and union types to Enc and adds encoding to cache.
6797/// Recursively calls appendType (via extractFieldType) for each field.
6798/// Union types have their fields ordered according to the ABI.
6799static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6800 const CodeGen::CodeGenModule &CGM,
6801 TypeStringCache &TSC, const IdentifierInfo *ID) {
6802 // Append the cached TypeString if we have one.
6803 StringRef TypeString = TSC.lookupStr(ID);
6804 if (!TypeString.empty()) {
6805 Enc += TypeString;
6806 return true;
6807 }
6808
6809 // Start to emit an incomplete TypeString.
6810 size_t Start = Enc.size();
6811 Enc += (RT->isUnionType()? 'u' : 's');
6812 Enc += '(';
6813 if (ID)
6814 Enc += ID->getName();
6815 Enc += "){";
6816
6817 // We collect all encoded fields and order as necessary.
6818 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006819 const RecordDecl *RD = RT->getDecl()->getDefinition();
6820 if (RD && !RD->field_empty()) {
6821 // An incomplete TypeString stub is placed in the cache for this RecordType
6822 // so that recursive calls to this RecordType will use it whilst building a
6823 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006824 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006825 std::string StubEnc(Enc.substr(Start).str());
6826 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6827 TSC.addIncomplete(ID, std::move(StubEnc));
6828 if (!extractFieldType(FE, RD, CGM, TSC)) {
6829 (void) TSC.removeIncomplete(ID);
6830 return false;
6831 }
6832 IsRecursive = TSC.removeIncomplete(ID);
6833 // The ABI requires unions to be sorted but not structures.
6834 // See FieldEncoding::operator< for sort algorithm.
6835 if (RT->isUnionType())
6836 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006837 // We can now complete the TypeString.
6838 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006839 for (unsigned I = 0; I != E; ++I) {
6840 if (I)
6841 Enc += ',';
6842 Enc += FE[I].str();
6843 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006844 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006845 Enc += '}';
6846 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6847 return true;
6848}
6849
6850/// Appends enum types to Enc and adds the encoding to the cache.
6851static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6852 TypeStringCache &TSC,
6853 const IdentifierInfo *ID) {
6854 // Append the cached TypeString if we have one.
6855 StringRef TypeString = TSC.lookupStr(ID);
6856 if (!TypeString.empty()) {
6857 Enc += TypeString;
6858 return true;
6859 }
6860
6861 size_t Start = Enc.size();
6862 Enc += "e(";
6863 if (ID)
6864 Enc += ID->getName();
6865 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006866
6867 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006868 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006869 SmallVector<FieldEncoding, 16> FE;
6870 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6871 ++I) {
6872 SmallStringEnc EnumEnc;
6873 EnumEnc += "m(";
6874 EnumEnc += I->getName();
6875 EnumEnc += "){";
6876 I->getInitVal().toString(EnumEnc);
6877 EnumEnc += '}';
6878 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6879 }
6880 std::sort(FE.begin(), FE.end());
6881 unsigned E = FE.size();
6882 for (unsigned I = 0; I != E; ++I) {
6883 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006884 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006885 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006886 }
6887 }
6888 Enc += '}';
6889 TSC.addIfComplete(ID, Enc.substr(Start), false);
6890 return true;
6891}
6892
6893/// Appends type's qualifier to Enc.
6894/// This is done prior to appending the type's encoding.
6895static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6896 // Qualifiers are emitted in alphabetical order.
6897 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6898 int Lookup = 0;
6899 if (QT.isConstQualified())
6900 Lookup += 1<<0;
6901 if (QT.isRestrictQualified())
6902 Lookup += 1<<1;
6903 if (QT.isVolatileQualified())
6904 Lookup += 1<<2;
6905 Enc += Table[Lookup];
6906}
6907
6908/// Appends built-in types to Enc.
6909static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6910 const char *EncType;
6911 switch (BT->getKind()) {
6912 case BuiltinType::Void:
6913 EncType = "0";
6914 break;
6915 case BuiltinType::Bool:
6916 EncType = "b";
6917 break;
6918 case BuiltinType::Char_U:
6919 EncType = "uc";
6920 break;
6921 case BuiltinType::UChar:
6922 EncType = "uc";
6923 break;
6924 case BuiltinType::SChar:
6925 EncType = "sc";
6926 break;
6927 case BuiltinType::UShort:
6928 EncType = "us";
6929 break;
6930 case BuiltinType::Short:
6931 EncType = "ss";
6932 break;
6933 case BuiltinType::UInt:
6934 EncType = "ui";
6935 break;
6936 case BuiltinType::Int:
6937 EncType = "si";
6938 break;
6939 case BuiltinType::ULong:
6940 EncType = "ul";
6941 break;
6942 case BuiltinType::Long:
6943 EncType = "sl";
6944 break;
6945 case BuiltinType::ULongLong:
6946 EncType = "ull";
6947 break;
6948 case BuiltinType::LongLong:
6949 EncType = "sll";
6950 break;
6951 case BuiltinType::Float:
6952 EncType = "ft";
6953 break;
6954 case BuiltinType::Double:
6955 EncType = "d";
6956 break;
6957 case BuiltinType::LongDouble:
6958 EncType = "ld";
6959 break;
6960 default:
6961 return false;
6962 }
6963 Enc += EncType;
6964 return true;
6965}
6966
6967/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6968static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6969 const CodeGen::CodeGenModule &CGM,
6970 TypeStringCache &TSC) {
6971 Enc += "p(";
6972 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6973 return false;
6974 Enc += ')';
6975 return true;
6976}
6977
6978/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006979static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6980 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006981 const CodeGen::CodeGenModule &CGM,
6982 TypeStringCache &TSC, StringRef NoSizeEnc) {
6983 if (AT->getSizeModifier() != ArrayType::Normal)
6984 return false;
6985 Enc += "a(";
6986 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6987 CAT->getSize().toStringUnsigned(Enc);
6988 else
6989 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6990 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006991 // The Qualifiers should be attached to the type rather than the array.
6992 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006993 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6994 return false;
6995 Enc += ')';
6996 return true;
6997}
6998
6999/// Appends a function encoding to Enc, calling appendType for the return type
7000/// and the arguments.
7001static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7002 const CodeGen::CodeGenModule &CGM,
7003 TypeStringCache &TSC) {
7004 Enc += "f{";
7005 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7006 return false;
7007 Enc += "}(";
7008 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7009 // N.B. we are only interested in the adjusted param types.
7010 auto I = FPT->param_type_begin();
7011 auto E = FPT->param_type_end();
7012 if (I != E) {
7013 do {
7014 if (!appendType(Enc, *I, CGM, TSC))
7015 return false;
7016 ++I;
7017 if (I != E)
7018 Enc += ',';
7019 } while (I != E);
7020 if (FPT->isVariadic())
7021 Enc += ",va";
7022 } else {
7023 if (FPT->isVariadic())
7024 Enc += "va";
7025 else
7026 Enc += '0';
7027 }
7028 }
7029 Enc += ')';
7030 return true;
7031}
7032
7033/// Handles the type's qualifier before dispatching a call to handle specific
7034/// type encodings.
7035static bool appendType(SmallStringEnc &Enc, QualType QType,
7036 const CodeGen::CodeGenModule &CGM,
7037 TypeStringCache &TSC) {
7038
7039 QualType QT = QType.getCanonicalType();
7040
Robert Lytton6adb20f2014-06-05 09:06:21 +00007041 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7042 // The Qualifiers should be attached to the type rather than the array.
7043 // Thus we don't call appendQualifier() here.
7044 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7045
Robert Lytton844aeeb2014-05-02 09:33:20 +00007046 appendQualifier(Enc, QT);
7047
7048 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7049 return appendBuiltinType(Enc, BT);
7050
Robert Lytton844aeeb2014-05-02 09:33:20 +00007051 if (const PointerType *PT = QT->getAs<PointerType>())
7052 return appendPointerType(Enc, PT, CGM, TSC);
7053
7054 if (const EnumType *ET = QT->getAs<EnumType>())
7055 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7056
7057 if (const RecordType *RT = QT->getAsStructureType())
7058 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7059
7060 if (const RecordType *RT = QT->getAsUnionType())
7061 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7062
7063 if (const FunctionType *FT = QT->getAs<FunctionType>())
7064 return appendFunctionType(Enc, FT, CGM, TSC);
7065
7066 return false;
7067}
7068
7069static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7070 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7071 if (!D)
7072 return false;
7073
7074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7075 if (FD->getLanguageLinkage() != CLanguageLinkage)
7076 return false;
7077 return appendType(Enc, FD->getType(), CGM, TSC);
7078 }
7079
7080 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7081 if (VD->getLanguageLinkage() != CLanguageLinkage)
7082 return false;
7083 QualType QT = VD->getType().getCanonicalType();
7084 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7085 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007086 // The Qualifiers should be attached to the type rather than the array.
7087 // Thus we don't call appendQualifier() here.
7088 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007089 }
7090 return appendType(Enc, QT, CGM, TSC);
7091 }
7092 return false;
7093}
7094
7095
Robert Lytton0e076492013-08-13 09:43:10 +00007096//===----------------------------------------------------------------------===//
7097// Driver code
7098//===----------------------------------------------------------------------===//
7099
Rafael Espindola9f834732014-09-19 01:54:22 +00007100const llvm::Triple &CodeGenModule::getTriple() const {
7101 return getTarget().getTriple();
7102}
7103
7104bool CodeGenModule::supportsCOMDAT() const {
7105 return !getTriple().isOSBinFormatMachO();
7106}
7107
Chris Lattner2b037972010-07-29 02:01:43 +00007108const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007109 if (TheTargetCodeGenInfo)
7110 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007111
John McCallc8e01702013-04-16 22:48:15 +00007112 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007113 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007114 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007115 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007116
Derek Schuff09338a22012-09-06 17:37:28 +00007117 case llvm::Triple::le32:
7118 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007119 case llvm::Triple::mips:
7120 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007121 if (Triple.getOS() == llvm::Triple::NaCl)
7122 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007123 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7124
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007125 case llvm::Triple::mips64:
7126 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007127 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7128
Tim Northover25e8a672014-05-24 12:51:25 +00007129 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007130 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007131 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007132 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007133 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007134
Tim Northover573cbee2014-05-24 12:52:07 +00007135 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007136 }
7137
Daniel Dunbard59655c2009-09-12 00:59:49 +00007138 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007139 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007140 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007141 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007142 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007143 if (Triple.getOS() == llvm::Triple::Win32) {
7144 TheTargetCodeGenInfo =
7145 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7146 return *TheTargetCodeGenInfo;
7147 }
7148
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007149 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007150 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007151 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007152 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007153 (CodeGenOpts.FloatABI != "soft" &&
7154 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007155 Kind = ARMABIInfo::AAPCS_VFP;
7156
Derek Schuff71658bd2015-01-29 00:47:04 +00007157 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007158 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007159
John McCallea8d8bb2010-03-11 00:10:12 +00007160 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007161 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007162 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007163 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007164 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007165 if (getTarget().getABI() == "elfv2")
7166 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007167 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007168
Ulrich Weigandb7122372014-07-21 00:48:09 +00007169 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007170 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007171 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007172 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007173 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007174 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007175 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007176 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007177 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007178 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007179
Ulrich Weigandb7122372014-07-21 00:48:09 +00007180 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007181 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007182 }
John McCallea8d8bb2010-03-11 00:10:12 +00007183
Peter Collingbournec947aae2012-05-20 23:28:41 +00007184 case llvm::Triple::nvptx:
7185 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007186 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007187
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007188 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007189 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007190
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007191 case llvm::Triple::systemz: {
7192 bool HasVector = getTarget().getABI() == "vector";
7193 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7194 HasVector));
7195 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007196
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007197 case llvm::Triple::tce:
7198 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7199
Eli Friedman33465822011-07-08 23:31:17 +00007200 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007201 bool IsDarwinVectorABI = Triple.isOSDarwin();
7202 bool IsSmallStructInRegABI =
7203 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007204 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007205
John McCall1fe2a8c2013-06-18 02:46:29 +00007206 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007207 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
7208 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7209 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007210 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007211 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
7212 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7213 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007214 }
Eli Friedman33465822011-07-08 23:31:17 +00007215 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007216
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007217 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007218 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007219 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7220 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007221 X86AVXABILevel::None);
7222
Chris Lattner04dc9572010-08-31 16:44:54 +00007223 switch (Triple.getOS()) {
7224 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007225 return *(TheTargetCodeGenInfo =
7226 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007227 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007228 return *(TheTargetCodeGenInfo =
7229 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007230 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007231 return *(TheTargetCodeGenInfo =
7232 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007233 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007234 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007235 case llvm::Triple::hexagon:
7236 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007237 case llvm::Triple::r600:
7238 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007239 case llvm::Triple::amdgcn:
7240 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007241 case llvm::Triple::sparcv9:
7242 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007243 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007244 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007245 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007246}